Map model object properties to DB(prepared statement)

@param mModelObj
@param preparedStatement
@throws D6Exception
556133
final void map(D6Model mModelObj, PreparedStatement preparedStatement, D6Inex includeExcludeColumnNames) throws D6Exception {

        log("#map obj=" + mModelObj);

        final Set<String> columnNameSet = getAllColumnNames();

        // index starts from 1
        int parameterIndex = 1;

        final List<String> columnNameList = new ArrayList<String>(columnNameSet);

        final List<Field> primaryKeyFieldList = getPrimaryKeyFieldList();

        for (Field field : primaryKeyFieldList) {
            DBColumn dbColumn = field.getAnnotation(DBColumn.class);
            String columnName = dbColumn.columnName();
            columnNameList.add(columnName);
        }

        // edit column names corresponding to include/exclude policy
        if (includeExcludeColumnNames != null) {
            includeExcludeColumnNames.manipulate(columnNameList);
        }

        // scan column by column
        for (String columnName : columnNameList) {

            final D6ModelClassFieldInfo fieldInfo = getFieldInfo(columnName);

            final boolean isNullable = fieldInfo.isNullable;

            final Field field = fieldInfo.field;
            final String fieldName = field.getName();

            final Class<?> type = field.getType();

            Object fieldValue = null;

            try {
                fieldValue = field.get(mModelObj);
            } catch (IllegalArgumentException e) {
                throw new D6Exception(e);
            } catch (IllegalAccessException e) {
                throw new D6Exception(e);
            }

            //
            if (fieldValue == null && isNullable == false) {
                // In case found the null-value column,
                // even though this item is NOT NULL
                throw new D6Exception("D6Error the model object field '" + fieldName + "'(column name is " + columnName + ") should not null." + "Because of constraint of table definition.");
            }

            try {

                log("#map idx=" + parameterIndex + " " + columnName + "=" + fieldValue + " (" + type + ")");

                setValue(parameterIndex, preparedStatement, type, fieldValue);

            } catch (Exception e) {
                throw new D6Exception(e);
            }

            parameterIndex++;

        }// end for (String columnName : columnNameList) {

    }
1339964
public static PreparedStatement prepareStatement(Connection conn, String sql, Collection<Object> params) throws SQLException {
		return prepareStatement(conn, sql, params.toArray(new Object[params.size()]));
	}
320369
private static void setBlob(PreparedStatement ps, int i, Object o, Class<?> cls)
            throws SQLException {
        final InputStream is;
        if (o instanceof byte[]) {
            is = new ByteArrayInputStream((byte[]) o);
        }
281832
public static void generateSQL(final SQLiteModelMethod method, MethodSpec.Builder methodBuilder) {
		JQLChecker jqlChecker = JQLChecker.getInstance();

		methodBuilder.addCode("\n// generate sql\n");
		String sql = jqlChecker.replace(method, method.jql, new JQLReplacerListenerImpl(method) {
			@Override
			public String onColumnNameToUpdate(String columnName) {
				// only entity's columns
				return currentEntity.findPropertyByName(columnName).columnName;
			}

			@Override
			public String onColumnName(String columnName) {
				return currentSchema.findColumnNameByPropertyName(method, columnName);
			}

			@Override
			public String onBindParameter(String bindParameterName, boolean inStatement) {
				return "?";
			}

		});

		if (method.jql.dynamicReplace.containsKey(JQLDynamicStatementType.DYNAMIC_WHERE)) {
			methodBuilder.addStatement("String _sql=String.format($S, $L)",
					sql.replace(method.jql.dynamicReplace.get(JQLDynamicStatementType.DYNAMIC_WHERE), "%s"),
					"StringUtils.ifNotEmptyAppend(_sqlDynamicWhere,\" AND \")");
		} else {
			methodBuilder.addStatement("String _sql=$S", sql);
		}
	}
1211485
public static int setKeyValuesAsParameterUsingPropertyColumn(SqlgGraph sqlgGraph, int i, PreparedStatement preparedStatement, Map<String, Pair<PropertyType, Object>> properties) throws SQLException {
        i = setKeyValuesAsParameterUsingPropertyColumn(sqlgGraph, true, i, preparedStatement, properties.values());
        return i;
    }
823479
public void bindSelect(PreparedStatement stmt, Identity oid, ClassDescriptor cld, boolean callableStmt) throws SQLException
    {
        ValueContainer[] values = null;
        int i = 0;
        int j = 0;

        if (cld == null)
        {
            cld = m_broker.getClassDescriptor(oid.getObjectsRealClass());
        }
        try
        {
            if(callableStmt)
            {
                // First argument is the result set
                m_platform.registerOutResultSet((CallableStatement) stmt, 1);
                j++;
            }

            values = getKeyValues(m_broker, cld, oid);
            for (/*void*/; i < values.length; i++, j++)
            {
                setObjectForStatement(stmt, j + 1, values[i].getValue(), values[i].getJdbcType().getType());
            }
        }
        catch (SQLException e)
        {
            m_log.error("bindSelect failed for: " + oid.toString() + ", PK: " + i + ", value: " + values[i]);
            throw e;
        }
    }
387337
private void cacheMetadata(ResultSetMetaData resultSetMetaData) throws SQLException {
        cachedColumnNames = new LinkedHashMap<String, Integer>();
        for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
            final String fieldTypeName = resultSetMetaData.getColumnTypeName(i);
            if (!fieldTypeName.equalsIgnoreCase("geometry")
                    && isSupportedPropertyType(resultSetMetaData.getColumnType(i), fieldTypeName)) {
                cachedColumnNames.put(resultSetMetaData.getColumnName(i).toUpperCase(), i);
                columnCountProperties++;
            }
        }
    }
41880
protected T cursorToObject(Cursor cursor) throws SQLException {
		return preparedQuery.mapRow(new AndroidDatabaseResults(cursor, null, true));
	}
18217
String getPreparedStatementText(ControlBeanContext context, Method m, Object[] args) {
        StringBuilder sb = new StringBuilder();
        for (SqlFragment sf : _children) {
            sb.append(sf.getPreparedStatementText(context, m, args));
        }
        return sb.toString();
    }
813707
@NotNull
    private BoundStatement createBoundStatement(@NotNull PreparedStatement prepare, @NotNull V entity, @NotNull List<ColumnMetadata> columns) {
        BoundStatement boundStatement = new BoundStatement(prepare);
        boundStatement.setConsistencyLevel(getEntityMetadata().getWriteConsistencyLevel());

        for (int i = 0; i < columns.size(); i++) {
            ColumnMetadata column = columns.get(i);

            Object value = column.readValue(entity);

            boundStatement.setBytesUnsafe(i, column.serialize(value));
        }

        return boundStatement;
    }
542069
protected void applyProperties(final PreparedStatement preparedStatement) throws SQLException {
		// フェッチサイズ指定
		if (getFetchSize() >= 0 && !(preparedStatement instanceof CallableStatement)) {
			preparedStatement.setFetchSize(getFetchSize());
		}

		// クエリタイムアウト指定
		if (getQueryTimeout() >= 0) {
			preparedStatement.setQueryTimeout(getQueryTimeout());
		}
	}
180782
@Override
    protected List<E> populateEntities(EntityMetadata m, Client client) throws Exception
    {
        int count = 0;
        List results = new ArrayList();
        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                m.getPersistenceUnit());
        EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz());
        Map<String, Object> relationalValues = new HashMap<String, Object>();
        if (rSet == null)
        {
            String parsedQuery = query.onQueryOverCQL3(m, client, metaModel, null);
            Statement statement = new SimpleStatement(parsedQuery);
            statement.setFetchSize(fetchSize);
            rSet = ((DSClient) client).executeStatement(statement);
            rowIter = rSet.iterator();
        }
        while (rowIter.hasNext() && count++ < fetchSize)
        {
            Object entity = null;
            Row row = rowIter.next();
            ((DSClient) client).populateObjectFromRow(entityMetadata, metaModel, entityType, results, relationalValues,
                    entity, row);
        }
        return results;
    }
317403
public void generateJavaDoc(MethodSpec.Builder methodBuilder, final SQLiteModelMethod method, TypeName returnType,
			List<SQLProperty> listUsedProperty, ModelProperty primaryKey) {
		// transform JQL to SQL
		String sqlInsert = JQLChecker.getInstance().replace(method, method.jql, new JQLReplacerListenerImpl(method) {

			@Override
			public String onColumnName(String columnName) {
				Set<SQLProperty> property = currentSchema.getPropertyBySimpleName(columnName);

				SQLProperty tempProperty = property.iterator().next();
				AssertKripton.assertTrueOrUnknownPropertyInJQLException(tempProperty != null, method, columnName);

				return tempProperty.columnName;
			}

			@Override
			public String onBindParameter(String bindParameterName, boolean inStatement) {
				String resolvedParamName = method.findParameterNameByAlias(bindParameterName);

				return SqlAnalyzer.PARAM_PREFIX + resolvedParamName + SqlAnalyzer.PARAM_SUFFIX;
			}

		});

		// generate javadoc and result
		{
			String beanNameParameter = method.findParameterAliasByName(method.getParameters().get(0).value0);

			methodBuilder.addJavadoc("<h2>SQL insert</h2>\n");
			methodBuilder.addJavadoc("<pre>$L</pre>\n\n", sqlInsert);
			methodBuilder.addJavadoc(
					"<p><code>$L.$L</code> is automatically updated because it is the primary key</p>\n",
					beanNameParameter, primaryKey.getName());
			methodBuilder.addJavadoc("\n");

			// list of inserted fields
			methodBuilder.addJavadoc("<p><strong>Inserted columns:</strong></p>\n");
			methodBuilder.addJavadoc("<dl>\n");
			for (SQLProperty property : listUsedProperty) {
				methodBuilder.addJavadoc("\t<dt>$L</dt>", property.columnName);
				methodBuilder.addJavadoc("<dd>is mapped to <strong>$L</strong></dd>\n",
						SqlAnalyzer.PARAM_PREFIX + method.findParameterAliasByName(method.getParameters().get(0).value0)
								+ "." + method.findParameterNameByAlias(property.getName()) + SqlAnalyzer.PARAM_SUFFIX);
			}
			methodBuilder.addJavadoc("</dl>\n\n");

			// update bean have only one parameter: the bean to update
			for (Pair<String, TypeName> param : method.getParameters()) {
				methodBuilder.addJavadoc("@param $L", param.value0);
				methodBuilder.addJavadoc("\n\tis mapped to parameter <strong>$L</strong>\n",
						method.findParameterAliasByName(param.value0));
			}

			InsertRawHelper.generateJavaDocReturnType(methodBuilder, returnType);
		}
	}
16878
public void processMappedStatement(MappedStatement ms){
        MapperTemplate mapperTemplate = isMapperMethod(ms.getId());
        if(mapperTemplate != null && ms.getSqlSource() instanceof ProviderSqlSource) {
            setSqlSource(ms, mapperTemplate);
        }
    }
259781
public static void prepareDataSource(DataSource ds) throws SQLException {
    Connection con = null;
    String sql;
    try {
      con = ds.getConnection();
      con.setAutoCommit(false);

      DatabaseMetaData meta = con.getMetaData();
      ResultSet rs = meta.getTables(null, null, null, new String[]{"TABLE"});
      int tableNameColumn = rs.findColumn("TABLE_NAME");
      int count = 0;
      while (rs.next()) {
        String tableName = rs.getString(tableNameColumn);
        if (tableName.equalsIgnoreCase("CachedClasses")) {
          count++;
        }
      }

      if (count == 0) {
        String blobType = DbUtil.getTypeName(Types.BLOB, con);
        String nameType = DbUtil.getTypeName(Types.VARCHAR, 1024, con);
        String md5Type = DbUtil.getTypeName(Types.BINARY, 16, con);

        sql =  "CREATE TABLE CachedClasses ( \n" +
            "  Name " + nameType + " NOT NULL, \n" +
            "  MD5 " + md5Type + " NOT NULL, \n" +
            "  Definition " + blobType + " NOT NULL, \n" +
            "  PRIMARY KEY (Name, MD5) \n" +
            ")";
        DbUtil.update(ds, sql);
        con.commit();
      }

      con.setAutoCommit(true);
    } catch (SQLException e) {
      DbUtil.rollback(con);
      throw e;
    } finally {
      DbUtil.close(con);
    }
  }
9361
public void bindUpdate(PreparedStatement stmt, ClassDescriptor cld, Object obj) throws java.sql.SQLException
    {
        if (cld.getUpdateProcedure() != null)
        {
            this.bindProcedure(stmt, cld, obj, cld.getUpdateProcedure());
        }
        else
        {
            int index = 1;
            ValueContainer[] values, valuesSnapshot;
            // first take a snapshot of current locking values
            valuesSnapshot = cld.getCurrentLockingValues(obj);
            cld.updateLockingValues(obj); // BRJ
            values = getNonKeyValues(m_broker, cld, obj);

            // parameters for SET-clause
            for (int i = 0; i < values.length; i++)
            {
                setObjectForStatement(stmt, index, values[i].getValue(), values[i].getJdbcType().getType());
                index++;
            }
            // parameters for WHERE-clause pk
            values = getKeyValues(m_broker, cld, obj);
            for (int i = 0; i < values.length; i++)
            {
                setObjectForStatement(stmt, index, values[i].getValue(), values[i].getJdbcType().getType());
                index++;
            }
            // parameters for WHERE-clause locking
            // take old locking values
            values = valuesSnapshot;
            for (int i = 0; i < values.length; i++)
            {
                setObjectForStatement(stmt, index, values[i].getValue(), values[i].getJdbcType().getType());
                index++;
            }
        }
    }
894066
public static void populateCompoundKey(DBObject dbObj, EntityMetadata m, MetamodelImpl metaModel, Object id)
    {
        EmbeddableType compoundKey = metaModel.embeddable(m.getIdAttribute().getBindableJavaType());
        // Iterator<Attribute> iter = compoundKey.getAttributes().iterator();
        BasicDBObject compoundKeyObj = new BasicDBObject();

        compoundKeyObj = getCompoundKeyColumns(m, id, compoundKey, metaModel);

        dbObj.put("_id", compoundKeyObj);
    }