Search in sources :

Example 1 with ReflectPropertyHandler

use of org.sagacity.sqltoy.callback.ReflectPropertyHandler in project sagacity-sqltoy by chenrenfei.

the class DialectUtils method updateAll.

/**
 * @todo 批量对象修改
 * @param sqlToyContext
 * @param entities
 * @param batchSize
 * @param forceUpdateFields
 * @param reflectPropertyHandler
 * @param nullFunction
 * @param conn
 * @param autoCommit
 * @param tableName
 * @throws Exception
 */
public static Long updateAll(SqlToyContext sqlToyContext, List<?> entities, final int batchSize, final String[] forceUpdateFields, ReflectPropertyHandler reflectPropertyHandler, String nullFunction, Connection conn, final Boolean autoCommit, String tableName) throws Exception {
    if (entities == null || entities.isEmpty())
        return new Long(0);
    EntityMeta entityMeta = sqlToyContext.getEntityMeta(entities.get(0).getClass());
    // 全部是主键则无需update,无主键则同样不符合修改规则
    if (entityMeta.getRejectIdFieldArray() == null || entityMeta.getIdArray() == null) {
        throw new Exception("表:" + entityMeta.getSchemaTable() + " 字段全部是主键或无主键,不符合update/updateAll规则,请检查表设计是否合理!");
    }
    // 构造全新的修改记录参数赋值反射(覆盖之前的)
    ReflectPropertyHandler handler = getUpdateReflectHandler(sqlToyContext, reflectPropertyHandler);
    List<Object[]> paramsValues = BeanUtil.reflectBeansToInnerAry(entities, entityMeta.getFieldsArray(), null, handler, false, 0);
    // 判断主键是否为空
    int pkIndex = entityMeta.getIdIndex();
    int end = pkIndex + entityMeta.getIdArray().length;
    int index = 0;
    for (Object[] rowValues : paramsValues) {
        for (int i = pkIndex; i < end; i++) {
            if (rowValues[i] == null)
                throw new Exception("通过对象进行updateAll操作,主键字段必须要赋值!第:" + index + " 条记录主键为null!");
        }
        index++;
    }
    // 构建update语句
    String updateSql = generateUpdateSql(entityMeta, nullFunction, forceUpdateFields, tableName);
    if (updateSql == null)
        throw new Exception("update sql is null,引起问题的原因是没有设置需要修改的字段!");
    if (sqlToyContext.isDebug())
        out.println("updateAll last execute sql:" + updateSql);
    return SqlUtilsExt.batchUpdateByJdbc(updateSql.toString(), paramsValues, batchSize, entityMeta.getFieldsTypeArray(), autoCommit, conn);
}
Also used : EntityMeta(org.sagacity.sqltoy.config.model.EntityMeta) ReflectPropertyHandler(org.sagacity.sqltoy.callback.ReflectPropertyHandler) SQLException(java.sql.SQLException) IOException(java.io.IOException)

Example 2 with ReflectPropertyHandler

use of org.sagacity.sqltoy.callback.ReflectPropertyHandler in project sagacity-sqltoy by chenrenfei.

the class DialectUtils method saveAll.

/**
 * @todo 保存批量对象数据
 * @param sqlToyContext
 * @param entityMeta
 * @param pkStrategy
 * @param isAssignPK
 * @param insertSql
 * @param entities
 * @param batchSize
 * @param reflectPropertyHandler
 * @param conn
 * @param autoCommit
 * @throws Exception
 */
public static Long saveAll(SqlToyContext sqlToyContext, EntityMeta entityMeta, PKStrategy pkStrategy, boolean isAssignPK, String insertSql, List<?> entities, final int batchSize, ReflectPropertyHandler reflectPropertyHandler, Connection conn, final Boolean autoCommit) throws Exception {
    boolean isIdentity = pkStrategy != null && pkStrategy.equals(PKStrategy.IDENTITY);
    boolean isSequence = pkStrategy != null && pkStrategy.equals(PKStrategy.SEQUENCE);
    String[] reflectColumns;
    if ((isIdentity && !isAssignPK) || (isSequence && !isAssignPK)) {
        reflectColumns = entityMeta.getRejectIdFieldArray();
    } else
        reflectColumns = entityMeta.getFieldsArray();
    // 构造全新的新增记录参数赋值反射(覆盖之前的)
    ReflectPropertyHandler handler = getAddReflectHandler(sqlToyContext, reflectPropertyHandler);
    List paramValues = BeanUtil.reflectBeansToInnerAry(entities, reflectColumns, null, handler, false, 0);
    int pkIndex = entityMeta.getIdIndex();
    // 是否存在业务ID
    boolean hasBizId = (entityMeta.getBusinessIdGenerator() == null) ? false : true;
    int bizIdColIndex = hasBizId ? entityMeta.getFieldIndex(entityMeta.getBusinessIdField()) : 0;
    // 标识符
    String signature = entityMeta.getBizIdSignature();
    Integer relatedColumn = entityMeta.getBizIdRelatedColIndex();
    // 无主键值以及多主键以及assign或通过generator方式产生主键策略
    if (pkStrategy != null && null != entityMeta.getIdGenerator()) {
        int bizIdLength = entityMeta.getBizIdLength();
        int idLength = entityMeta.getIdLength();
        Object[] rowData;
        boolean isAssigned = true;
        int idJdbcType = entityMeta.getIdType();
        Object relatedColValue = null;
        int businessIdType = hasBizId ? entityMeta.getColumnType(entityMeta.getBusinessIdField()) : 0;
        List<Object[]> idSet = new ArrayList<Object[]>();
        for (int i = 0, s = paramValues.size(); i < s; i++) {
            rowData = (Object[]) paramValues.get(i);
            if (relatedColumn != null) {
                relatedColValue = rowData[relatedColumn];
            }
            if (StringUtil.isBlank(rowData[pkIndex])) {
                isAssigned = false;
                rowData[pkIndex] = entityMeta.getIdGenerator().getId(entityMeta.getTableName(), signature, relatedColValue, null, idJdbcType, idLength);
            }
            if (hasBizId && StringUtil.isBlank(rowData[bizIdColIndex])) {
                rowData[bizIdColIndex] = entityMeta.getBusinessIdGenerator().getId(entityMeta.getTableName(), signature, relatedColValue, null, businessIdType, bizIdLength);
                // 回写业务主键值
                BeanUtils.setProperty(entities.get(i), entityMeta.getBusinessIdField(), rowData[bizIdColIndex]);
            }
            idSet.add(new Object[] { rowData[pkIndex] });
        }
        // 批量反向设置最终得到的主键值
        if (!isAssigned) {
            BeanUtil.mappingSetProperties(entities, entityMeta.getIdArray(), idSet, new int[] { 0 }, true);
        }
    }
    if (sqlToyContext.isDebug())
        out.println("batch insert sql:" + insertSql);
    return SqlUtilsExt.batchUpdateByJdbc(insertSql, paramValues, batchSize, entityMeta.getFieldsTypeArray(), autoCommit, conn);
}
Also used : ArrayList(java.util.ArrayList) List(java.util.List) ArrayList(java.util.ArrayList) ReflectPropertyHandler(org.sagacity.sqltoy.callback.ReflectPropertyHandler)

Example 3 with ReflectPropertyHandler

use of org.sagacity.sqltoy.callback.ReflectPropertyHandler in project sagacity-sqltoy by chenrenfei.

the class DialectUtils method save.

/**
 * @todo 保存对象
 * @param sqlToyContext
 * @param entityMeta
 * @param pkStrategy
 * @param isAssignPK
 * @param returnPkType
 * @param insertSql
 * @param entity
 * @param generateSqlHandler
 * @param generateSavePKStrategy
 * @param conn
 * @return
 * @throws Exception
 */
public static Object save(SqlToyContext sqlToyContext, final EntityMeta entityMeta, final PKStrategy pkStrategy, final boolean isAssignPK, final ReturnPkType returnPkType, final String insertSql, Serializable entity, final GenerateSqlHandler generateSqlHandler, final GenerateSavePKStrategy generateSavePKStrategy, final Connection conn) throws Exception {
    final boolean isIdentity = (pkStrategy != null && pkStrategy.equals(PKStrategy.IDENTITY));
    final boolean isSequence = (pkStrategy != null && pkStrategy.equals(PKStrategy.SEQUENCE));
    String[] reflectColumns;
    if ((isIdentity && !isAssignPK) || (isSequence && !isAssignPK)) {
        reflectColumns = entityMeta.getRejectIdFieldArray();
    } else
        reflectColumns = entityMeta.getFieldsArray();
    // 构造全新的新增记录参数赋值反射(覆盖之前的)
    ReflectPropertyHandler handler = getAddReflectHandler(sqlToyContext, null);
    Object[] fullParamValues = BeanUtil.reflectBeanToAry(entity, reflectColumns, null, handler);
    boolean needUpdatePk = false;
    // 无主键,或多主键且非identity、sequence模式
    boolean noPK = (entityMeta.getIdArray() == null);
    int pkIndex = entityMeta.getIdIndex();
    // 是否存在业务ID
    boolean hasBizId = (entityMeta.getBusinessIdGenerator() == null) ? false : true;
    int bizIdColIndex = hasBizId ? entityMeta.getFieldIndex(entityMeta.getBusinessIdField()) : 0;
    // 标识符
    String signature = entityMeta.getBizIdSignature();
    Integer relatedColumn = entityMeta.getBizIdRelatedColIndex();
    // 主键采用assign方式赋予,则调用generator产生id并赋予其值
    if (entityMeta.getIdStrategy() != null && null != entityMeta.getIdGenerator()) {
        int bizIdLength = entityMeta.getBizIdLength();
        int idLength = entityMeta.getIdLength();
        Object relatedColValue = null;
        int businessIdType = hasBizId ? entityMeta.getColumnType(entityMeta.getBusinessIdField()) : 0;
        if (relatedColumn != null) {
            relatedColValue = fullParamValues[relatedColumn];
        }
        if (StringUtil.isBlank(fullParamValues[pkIndex])) {
            // id通过generator机制产生,设置generator产生的值
            fullParamValues[pkIndex] = entityMeta.getIdGenerator().getId(entityMeta.getSchemaTable(), signature, relatedColValue, null, entityMeta.getIdType(), idLength);
            needUpdatePk = true;
        }
        if (hasBizId && StringUtil.isBlank(fullParamValues[bizIdColIndex])) {
            fullParamValues[bizIdColIndex] = entityMeta.getBusinessIdGenerator().getId(entityMeta.getTableName(), signature, relatedColValue, null, businessIdType, bizIdLength);
            // 回写业务主键值
            BeanUtils.setProperty(entity, entityMeta.getBusinessIdField(), fullParamValues[bizIdColIndex]);
        }
    }
    if (sqlToyContext.isDebug())
        out.println(insertSql);
    final Object[] paramValues = fullParamValues;
    final Integer[] paramsType = entityMeta.getFieldsTypeArray();
    PreparedStatement pst = null;
    Object result = SqlUtil.preparedStatementProcess(null, pst, null, new PreparedStatementResultHandler() {

        public void execute(Object obj, PreparedStatement pst, ResultSet rs) throws SQLException, IOException {
            if (isIdentity || isSequence) {
                if (returnPkType.equals(ReturnPkType.GENERATED_KEYS))
                    pst = conn.prepareStatement(insertSql, PreparedStatement.RETURN_GENERATED_KEYS);
                else if (returnPkType.equals(ReturnPkType.PREPARD_ID))
                    pst = conn.prepareStatement(insertSql, new String[] { entityMeta.getColumnName(entityMeta.getIdArray()[0]) });
                else
                    pst = conn.prepareStatement(insertSql);
            } else
                pst = conn.prepareStatement(insertSql);
            SqlUtil.setParamsValue(conn, pst, paramValues, paramsType, 0);
            ResultSet keyResult = null;
            if ((isIdentity || isSequence) && returnPkType.equals(ReturnPkType.RESULT_GET))
                keyResult = pst.executeQuery();
            else
                pst.execute();
            if (isIdentity || isSequence) {
                if (!returnPkType.equals(ReturnPkType.RESULT_GET))
                    keyResult = pst.getGeneratedKeys();
                if (keyResult != null) {
                    List result = new ArrayList();
                    while (keyResult.next()) result.add(keyResult.getObject(1));
                    if (result.size() == 1)
                        this.setResult(result.get(0));
                    else
                        this.setResult(result.toArray());
                }
            }
        }
    });
    // 无主键直接返回null
    if (noPK)
        return null;
    else {
        if (result == null)
            result = fullParamValues[pkIndex];
        // 回置到entity 主键值
        if (needUpdatePk || isIdentity || isSequence) {
            BeanUtils.setProperty(entity, entityMeta.getIdArray()[0], result);
        }
        // 判定是否有级联子表数据保存
        if (!entityMeta.getOneToManys().isEmpty()) {
            List subTableData;
            final Object[] idValues = BeanUtil.reflectBeanToAry(entity, entityMeta.getIdArray(), null, null);
            EntityMeta subTableEntityMeta;
            String insertSubTableSql;
            SavePKStrategy savePkStrategy;
            for (OneToManyModel oneToMany : entityMeta.getOneToManys()) {
                final String[] mappedFields = oneToMany.getMappedFields();
                subTableEntityMeta = sqlToyContext.getEntityMeta(oneToMany.getMappedType());
                subTableData = (List) PropertyUtils.getProperty(entity, oneToMany.getProperty());
                if (subTableData != null && !subTableData.isEmpty()) {
                    insertSubTableSql = generateSqlHandler.generateSql(subTableEntityMeta, null);
                    savePkStrategy = generateSavePKStrategy.generate(subTableEntityMeta);
                    saveAll(sqlToyContext, subTableEntityMeta, savePkStrategy.getPkStrategy(), savePkStrategy.isAssginValue(), insertSubTableSql, subTableData, sqlToyContext.getBatchSize(), new ReflectPropertyHandler() {

                        public void process() {
                            for (int i = 0; i < mappedFields.length; i++) {
                                this.setValue(mappedFields[i], idValues[i]);
                            }
                        }
                    }, conn, null);
                }
            }
        }
        return result;
    }
}
Also used : EntityMeta(org.sagacity.sqltoy.config.model.EntityMeta) SQLException(java.sql.SQLException) PreparedStatementResultHandler(org.sagacity.sqltoy.callback.PreparedStatementResultHandler) ArrayList(java.util.ArrayList) PreparedStatement(java.sql.PreparedStatement) IOException(java.io.IOException) ResultSet(java.sql.ResultSet) List(java.util.List) ArrayList(java.util.ArrayList) ReflectPropertyHandler(org.sagacity.sqltoy.callback.ReflectPropertyHandler) OneToManyModel(org.sagacity.sqltoy.config.model.OneToManyModel) GenerateSavePKStrategy(org.sagacity.sqltoy.dialect.handler.GenerateSavePKStrategy) SavePKStrategy(org.sagacity.sqltoy.dialect.model.SavePKStrategy)

Example 4 with ReflectPropertyHandler

use of org.sagacity.sqltoy.callback.ReflectPropertyHandler in project sagacity-sqltoy by chenrenfei.

the class DialectUtils method getAddReflectHandler.

/**
 * @todo 构造新增记录参数反射赋值处理器
 * @param sqlToyContext
 * @param preHandler
 * @return
 */
public static ReflectPropertyHandler getAddReflectHandler(SqlToyContext sqlToyContext, final ReflectPropertyHandler preHandler) {
    if (sqlToyContext.getUnifyFieldsHandler() == null)
        return preHandler;
    final Map<String, Object> keyValues = sqlToyContext.getUnifyFieldsHandler().createUnifyFields();
    if (keyValues == null || keyValues.isEmpty())
        return preHandler;
    ReflectPropertyHandler handler = new ReflectPropertyHandler() {

        @Override
        public void process() {
            if (preHandler != null) {
                preHandler.setPropertyIndexMap(this.getPropertyIndexMap());
                preHandler.setRowIndex(this.getRowIndex());
                preHandler.setRowData(this.getRowData());
                preHandler.process();
            }
            for (Map.Entry<String, Object> entry : keyValues.entrySet()) {
                if (StringUtil.isBlank(this.getValue(entry.getKey())))
                    this.setValue(entry.getKey(), entry.getValue());
            }
        }
    };
    return handler;
}
Also used : ReflectPropertyHandler(org.sagacity.sqltoy.callback.ReflectPropertyHandler) Map(java.util.Map) HashMap(java.util.HashMap)

Example 5 with ReflectPropertyHandler

use of org.sagacity.sqltoy.callback.ReflectPropertyHandler in project sagacity-sqltoy by chenrenfei.

the class SqlServerDialectUtils method saveAll.

/**
 * @todo 保存批量对象数据
 * @param sqlToyContext
 * @param entityMeta
 * @param pkStrategy
 * @param isAssignPK
 * @param insertSql
 * @param entities
 * @param reflectPropertyHandler
 * @param conn
 * @param autoCommit
 * @throws Exception
 */
private static Long saveAll(SqlToyContext sqlToyContext, EntityMeta entityMeta, PKStrategy pkStrategy, boolean isAssignPK, String insertSql, List<?> entities, ReflectPropertyHandler reflectPropertyHandler, Connection conn, final Boolean autoCommit) throws Exception {
    boolean isIdentity = pkStrategy != null && pkStrategy.equals(PKStrategy.IDENTITY);
    boolean isSequence = pkStrategy != null && pkStrategy.equals(PKStrategy.SEQUENCE);
    String[] reflectColumns;
    if ((isIdentity && !isAssignPK) || (isSequence && !isAssignPK)) {
        reflectColumns = entityMeta.getRejectIdFieldArray();
    } else
        reflectColumns = entityMeta.getFieldsArray();
    ReflectPropertyHandler handler = DialectUtils.getAddReflectHandler(sqlToyContext, reflectPropertyHandler);
    List<Object[]> paramValues = BeanUtil.reflectBeansToInnerAry(entities, reflectColumns, null, handler, false, 0);
    int pkIndex = entityMeta.getIdIndex();
    // 是否存在业务ID
    boolean hasBizId = (entityMeta.getBusinessIdGenerator() == null) ? false : true;
    int bizIdColIndex = hasBizId ? entityMeta.getFieldIndex(entityMeta.getBusinessIdField()) : 0;
    // 标识符
    String signature = entityMeta.getBizIdSignature();
    Integer relatedColumn = entityMeta.getBizIdRelatedColIndex();
    // 无主键值以及多主键以及assign或通过generator方式产生主键策略
    if (pkStrategy != null && null != entityMeta.getIdGenerator()) {
        int idLength = entityMeta.getIdLength();
        int bizIdLength = entityMeta.getBizIdLength();
        Object[] rowData;
        boolean isAssigned = true;
        List<Object[]> idSet = new ArrayList<Object[]>();
        int idJdbcType = entityMeta.getIdType();
        Object relatedColValue = null;
        int businessIdType = hasBizId ? entityMeta.getColumnType(entityMeta.getBusinessIdField()) : 0;
        for (int i = 0, s = paramValues.size(); i < s; i++) {
            rowData = (Object[]) paramValues.get(i);
            if (relatedColumn != null) {
                relatedColValue = rowData[relatedColumn];
            }
            if (StringUtil.isBlank(rowData[pkIndex])) {
                isAssigned = false;
                rowData[pkIndex] = entityMeta.getIdGenerator().getId(entityMeta.getTableName(), signature, relatedColValue, null, idJdbcType, idLength);
            }
            if (hasBizId && StringUtil.isBlank(rowData[bizIdColIndex])) {
                rowData[bizIdColIndex] = entityMeta.getBusinessIdGenerator().getId(entityMeta.getTableName(), signature, relatedColValue, null, businessIdType, bizIdLength);
                // 回写业务主键值
                BeanUtils.setProperty(entities.get(i), entityMeta.getBusinessIdField(), rowData[bizIdColIndex]);
            }
            idSet.add(new Object[] { rowData[pkIndex] });
        }
        // 批量反向设置最终得到的主键值
        if (!isAssigned) {
            BeanUtil.mappingSetProperties(entities, entityMeta.getIdArray(), idSet, new int[] { 0 }, true);
        }
    }
    if (sqlToyContext.isDebug())
        out.println("batch insert sql:" + insertSql);
    return batchUpdateByJdbc(insertSql, paramValues, sqlToyContext.getBatchSize(), entityMeta.getFieldsTypeArray(), autoCommit, conn);
}
Also used : ArrayList(java.util.ArrayList) ReflectPropertyHandler(org.sagacity.sqltoy.callback.ReflectPropertyHandler)

Aggregations

ReflectPropertyHandler (org.sagacity.sqltoy.callback.ReflectPropertyHandler)16 ArrayList (java.util.ArrayList)9 List (java.util.List)7 EntityMeta (org.sagacity.sqltoy.config.model.EntityMeta)6 IOException (java.io.IOException)5 SQLException (java.sql.SQLException)5 HashMap (java.util.HashMap)5 OneToManyModel (org.sagacity.sqltoy.config.model.OneToManyModel)5 PreparedStatement (java.sql.PreparedStatement)3 ResultSet (java.sql.ResultSet)3 Map (java.util.Map)3 PreparedStatementResultHandler (org.sagacity.sqltoy.callback.PreparedStatementResultHandler)3 Type (java.lang.reflect.Type)2 SqlToyResult (org.sagacity.sqltoy.config.model.SqlToyResult)2 Test (org.junit.Test)1 SqlType (org.sagacity.sqltoy.config.model.SqlType)1 GenerateSavePKStrategy (org.sagacity.sqltoy.dialect.handler.GenerateSavePKStrategy)1 ReturnPkType (org.sagacity.sqltoy.dialect.model.ReturnPkType)1 SavePKStrategy (org.sagacity.sqltoy.dialect.model.SavePKStrategy)1 DBType (org.sagacity.sqltoy.utils.DataSourceUtils.DBType)1