All Downloads are FREE. Search and download functionalities are using the official Maven repository.

rb.templates.persistence_impl.erb Maven / Gradle / Ivy

There is a newer version: 1.8
Show newest version
<%#
# Copyright 2011 Rapleaf
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
%>
<%= autogenerated %>
package <%= root_package %>.impl;

import java.sql.SQLRecoverableException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Date;
import java.sql.Timestamp;

import <%= JACK_NAMESPACE %>.AbstractDatabaseModel;
import <%= JACK_NAMESPACE %>.BaseDatabaseConnection;
import <%= JACK_NAMESPACE %>.queries.WhereConstraint;
import <%= JACK_NAMESPACE %>.queries.WhereClause;
import <%= JACK_NAMESPACE %>.util.JackUtility;
import <%= root_package %>.iface.<%= model_defn.iface_name %>;
import <%= root_package %>.models.<%= model_defn.model_name %>;
import <%= root_package %>.query.<%= model_defn.query_builder_name %>;
import <%= root_package %>.query.<%= model_defn.delete_builder_name %>;

import <%= project_defn.databases_namespace %>.IDatabases;

public class <%= model_defn.impl_name %> extends AbstractDatabaseModel<<%= model_defn.model_name %>> implements <%= model_defn.iface_name %> {
  private final IDatabases databases;

  public <%= model_defn.impl_name %>(BaseDatabaseConnection conn, IDatabases databases) {
    super(conn, "<%= model_defn.table_name %>", Arrays.asList(<%= model_defn.fields.map{|x| "\"#{x.name}\""}.join(", ") %>));
    this.databases = databases;
  }

  @Override
  public <%= model_defn.model_name %> create(Map fieldsMap) throws IOException {
    <% model_defn.fields.each do |field_defn| %>
    <% if field_defn.default_value.nil? %>
    <%= field_defn.java_type %> <%= field_defn.name %> = (<%= field_defn.java_type(true) %>) fieldsMap.get(<%= model_defn.model_name %>._Fields.<%= field_defn.name %>);
    <% else %>
    <%= field_defn.java_type(true) %> <%= field_defn.name %>_tmp = (<%= field_defn.java_type(true) %>) fieldsMap.get(<%= model_defn.model_name %>._Fields.<%= field_defn.name %>);
    <%= field_defn.java_type %> <%= field_defn.name %> = <%= field_defn.name %>_tmp == null ? <%= field_defn.default_value %> : <%= field_defn.name %>_tmp;
    <% end %>
    <% end %>
    return create(<%= model_defn.fields.map{|field| field.name }.join(', ') %>);
  }

  <%= render_create_method(model_defn, create_signature_full) %>
  <% unless create_signature_small.nil? %>
    <%= render_create_method(model_defn, create_signature_small, true) %>
  <% end %>

  public <%= model_defn.model_name %> createDefaultInstance() throws IOException {
    return create(<%= create_argument_defaults %>);
  }

  public List<<%= model_defn.model_name %>> find(Map fieldsMap) throws IOException {
    return find(null, fieldsMap);
  }

  public List<<%= model_defn.model_name %>> find(Collection ids, Map fieldsMap) throws IOException {
    List<<%= model_defn.model_name %>> foundList = new ArrayList<>();

    if (fieldsMap == null || fieldsMap.isEmpty()) {
      return foundList;
    }

    StringBuilder statementString = new StringBuilder();
    statementString.append("SELECT * FROM <%= model_defn.table_name %> WHERE (");
    List nonNullValues = new ArrayList<>();
    List<<%= model_defn.model_name %>._Fields> nonNullValueFields = new ArrayList<>();

    Iterator> iter = fieldsMap.entrySet().iterator();
    while (iter.hasNext()) {
      Map.Entry entry = iter.next();
      Enum field = entry.getKey();
      Object value = entry.getValue();

      String queryValue = value != null ? " = ? " : " IS NULL";
      if (value != null) {
        nonNullValueFields.add((<%= model_defn.model_name %>._Fields) field);
        nonNullValues.add(value);
      }

      statementString.append(field).append(queryValue);
      if (iter.hasNext()) {
        statementString.append(" AND ");
      }
    }
    if (ids != null) statementString.append(" AND ").append(getIdSetCondition(ids));
    statementString.append(")");

    int retryCount = 0;
    PreparedStatement preparedStatement;

    while (true) {
      preparedStatement = getPreparedStatement(statementString.toString());

      <% if ! model_defn.fields.empty? %>

      for (int i = 0; i < nonNullValues.size(); i++) {
        <%= model_defn.model_name %>._Fields field = nonNullValueFields.get(i);
        try {
          switch (field) {
      <% model_defn.fields.each do |field_defn| %>
            case <%= field_defn.name %>:
              preparedStatement.set<%=field_defn.prep_stmt_type%>(i+1, <%=field_defn.prep_stmt_modifier("(#{field_defn.java_type(true)}) nonNullValues.get(i)")%>);
              break;
      <% end %>
          }
        } catch (SQLException e) {
          throw new IOException(e);
        }
      }
      <% end %>

      try {
        executeQuery(foundList, preparedStatement);
        return foundList;
      } catch (SQLRecoverableException e) {
        if (++retryCount > AbstractDatabaseModel.MAX_CONNECTION_RETRIES) {
          throw new IOException(e);
        }
      } catch (SQLException e) {
        throw new IOException(e);
      }
    }
  }

  @Override
  protected void setStatementParameters(PreparedStatement preparedStatement, WhereClause whereClause) throws IOException {
    <% if model_defn.fields.empty? %>
    throw new RuntimeException("No parameters to set for " + getClass().getCanonicalName());
    <% else %>
    int index = 0;
    for (WhereConstraint constraint : whereClause.getWhereConstraints()) {
      for (Object parameter : constraint.getParameters()) {
        if (parameter == null) {
          continue;
        }
        try {
          if (constraint.isId()) {
            preparedStatement.setLong(++index, (Long)parameter);
          } else {
            <%= model_defn.model_name %>._Fields field = (<%= model_defn.model_name %>._Fields)constraint.getField();
            switch (field) {
        <% model_defn.fields.each do |field_defn| %>
              case <%= field_defn.name %>:
                preparedStatement.set<%=field_defn.prep_stmt_type%>(++index, <%=field_defn.prep_stmt_modifier("(#{field_defn.java_type(true)}) parameter")%>);
                break;
        <% end %>
            }
          }
        } catch (SQLException e) {
          throw new IOException(e);
        }
      }
    }
    <% end %>
  }

  @Override
  protected void setAttrs(<%= model_defn.model_name %> model, PreparedStatement stmt, boolean setNull) throws SQLException {
    int index = 1;
    <% model_defn.fields.each do |field_defn| %>
    <% if field_defn.nullable? %>
    if (setNull && model.<%= field_defn.getter %> == null) {
      stmt.setNull(index++, java.sql.Types.<%= field_defn.sql_type %>);
    } else if (model.<%= field_defn.getter %> != null) {
    <% else %>
    {
    <% end %>
    <% if field_defn.name == "lock_version" and field_defn.data_type == :integer  %>
      stmt.set<%= field_defn.prep_stmt_type %>(index++, <%= field_defn.prep_stmt_modifier("model.#{field_defn.getter} + 1") %>);
    <% else %>
      stmt.set<%= field_defn.prep_stmt_type %>(index++, <%= field_defn.prep_stmt_modifier("model.#{field_defn.getter}") %>);
    <% end %>
    }
    <% end %>
    stmt.setLong(index, model.getId());
  }

  @Override
  protected <%= model_defn.model_name %> instanceFromResultSet(ResultSet rs, Collection selectedFields) throws SQLException {
    boolean allFields = selectedFields == null || selectedFields.isEmpty();
    <% if database_defn.support_missing_id %>
    long id = JackUtility.hasColumn(rs, "id") ? rs.getLong("id") : -1;
    <% else %>
    long id = rs.getLong("id");
    <% end %>
    return new <%= model_defn.model_name %>(id,
    <% model_defn.fields.each do |field_defn| %>
      allFields || selectedFields.contains(<%= model_defn.model_name %>._Fields.<%=field_defn.name%>) ? <%= field_defn.get_from_rs %> : <%= field_defn.nullable? ? "null" : field_defn.java_default_value %>,
    <% end %>
      databases
    );
  }

  <% model_defn.fields.each do |field_defn| %>

  public List<<%= model_defn.model_name %>> findBy<%= field_defn.name.camelcase %>(final <%= field_defn.java_type %> value) throws IOException {
    return find(Collections.singletonMap(<%= model_defn.model_name %>._Fields.<%= field_defn.name %>, value));
  }
  <% end %>

  public <%= model_defn.query_builder_name %> query() {
    return new <%= model_defn.query_builder_name %>(this);
  }

  public <%= model_defn.delete_builder_name %> delete() {
    return new <%= model_defn.delete_builder_name %>(this);
  }
}