Search in sources :

Example 11 with ReflectPropertyHandler

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

the class DialectUtils method update.

/**
 * @todo 单个对象修改,包含接连修改
 * @param sqlToyContext
 * @param entity
 * @param nullFunction
 * @param forceUpdateFields
 * @param cascade
 * @param generateSqlHandler
 * @param forceCascadeClasses
 * @param subTableForceUpdateProps
 * @param conn
 * @param tableName
 * @throws Exception
 */
public static Long update(SqlToyContext sqlToyContext, Serializable entity, String nullFunction, String[] forceUpdateFields, final boolean cascade, final GenerateSqlHandler generateSqlHandler, final Class[] forceCascadeClasses, final HashMap<Class, String[]> subTableForceUpdateProps, Connection conn, String tableName) throws Exception {
    EntityMeta entityMeta = sqlToyContext.getEntityMeta(entity.getClass());
    Long updateCnt = update(sqlToyContext, entity, entityMeta, nullFunction, forceUpdateFields, conn, tableName);
    // 级联保存
    if (cascade && !entityMeta.getOneToManys().isEmpty()) {
        HashMap<Type, String> typeMap = new HashMap<Type, String>();
        // 即使子对象数据是null,也强制进行级联修改(null表示删除子表数据)
        if (forceCascadeClasses != null) {
            for (Type type : forceCascadeClasses) {
                typeMap.put(type, "");
            }
        }
        // 级联子表数据
        List subTableData;
        final Object[] IdValues = BeanUtil.reflectBeanToAry(entity, entityMeta.getIdArray(), null, null);
        String[] forceUpdateProps = null;
        EntityMeta subTableEntityMeta;
        // 对子表进行级联处理
        for (OneToManyModel oneToMany : entityMeta.getOneToManys()) {
            subTableEntityMeta = sqlToyContext.getEntityMeta(oneToMany.getMappedType());
            forceUpdateProps = (subTableForceUpdateProps == null) ? null : subTableForceUpdateProps.get(oneToMany.getMappedType());
            subTableData = (List) BeanUtil.invokeMethod(entity, "get".concat(StringUtil.firstToUpperCase(oneToMany.getProperty())), null);
            final String[] mappedFields = oneToMany.getMappedFields();
            /**
             * 针对子表存量数据,调用级联修改的语句,分delete 和update两种操作 1、删除存量数据;2、设置存量数据状态为停用
             */
            if (oneToMany.getCascadeUpdateSql() != null && ((subTableData != null && !subTableData.isEmpty()) || typeMap.containsKey(oneToMany.getMappedType()))) {
                // 根据quickvo配置文件针对cascade中update-cascade配置组织具体操作sql
                SqlToyResult sqlToyResult = SqlConfigParseUtils.processSql(oneToMany.getCascadeUpdateSql(), mappedFields, IdValues);
                executeSql(sqlToyResult.getSql(), sqlToyResult.getParamsValue(), null, conn, null);
            }
            // 子表数据不为空,采取saveOrUpdateAll操作
            if (subTableData != null && !subTableData.isEmpty()) {
                saveOrUpdateAll(sqlToyContext, subTableData, sqlToyContext.getBatchSize(), subTableEntityMeta, forceUpdateProps, generateSqlHandler, // 设置关联外键字段的属性值(来自主表的主键)
                new ReflectPropertyHandler() {

                    public void process() {
                        for (int i = 0; i < mappedFields.length; i++) {
                            this.setValue(mappedFields[i], IdValues[i]);
                        }
                    }
                }, conn, null);
            }
        }
    }
    return updateCnt;
}
Also used : EntityMeta(org.sagacity.sqltoy.config.model.EntityMeta) HashMap(java.util.HashMap) SqlToyResult(org.sagacity.sqltoy.config.model.SqlToyResult) ReturnPkType(org.sagacity.sqltoy.dialect.model.ReturnPkType) Type(java.lang.reflect.Type) List(java.util.List) ArrayList(java.util.ArrayList) ReflectPropertyHandler(org.sagacity.sqltoy.callback.ReflectPropertyHandler) OneToManyModel(org.sagacity.sqltoy.config.model.OneToManyModel)

Example 12 with ReflectPropertyHandler

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

the class DialectUtils method getSaveOrUpdateReflectHandler.

/**
 * @todo 构造创建和修改记录时的反射
 * @param sqlToyContext
 * @param idFields
 * @param preHandler
 * @return
 */
public static ReflectPropertyHandler getSaveOrUpdateReflectHandler(SqlToyContext sqlToyContext, final String[] idFields, final ReflectPropertyHandler preHandler) {
    if (sqlToyContext.getUnifyFieldsHandler() == null)
        return preHandler;
    final Map<String, Object> addKeyValues = sqlToyContext.getUnifyFieldsHandler().createUnifyFields();
    final Map<String, Object> updateKeyValues = sqlToyContext.getUnifyFieldsHandler().updateUnifyFields();
    if ((addKeyValues == null || addKeyValues.isEmpty()) && (updateKeyValues == null || updateKeyValues.isEmpty()))
        return preHandler;
    final int idLength = (idFields == null) ? 0 : idFields.length;
    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();
            }
            // 主键为空表示save操作
            if (idLength > 0 && this.getValue(idFields[0]) == null) {
                for (Map.Entry<String, Object> entry : addKeyValues.entrySet()) {
                    if (StringUtil.isBlank(this.getValue(entry.getKey()))) {
                        this.setValue(entry.getKey(), entry.getValue());
                    }
                }
            }
            // 修改属性值
            for (Map.Entry<String, Object> entry : updateKeyValues.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 13 with ReflectPropertyHandler

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

the class DialectUtils method saveOrUpdateAll.

/**
 * @todo 执行批量保存或修改操作
 * @param sqlToyContext
 * @param sql
 * @param entities
 * @param entityMeta
 * @param reflectPropertyHandler
 * @param conn
 * @param autoCommit
 * @throws Exception
 */
public static Long saveOrUpdateAll(SqlToyContext sqlToyContext, List<?> entities, final int batchSize, EntityMeta entityMeta, String[] forceUpdateFields, GenerateSqlHandler generateSqlHandler, ReflectPropertyHandler reflectPropertyHandler, Connection conn, Boolean autoCommit) throws Exception {
    // 重新构造修改或保存的属性赋值反调
    ReflectPropertyHandler handler = getSaveOrUpdateReflectHandler(sqlToyContext, entityMeta.getIdArray(), reflectPropertyHandler);
    List<Object[]> paramValues = BeanUtil.reflectBeansToInnerAry(entities, entityMeta.getFieldsArray(), 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 (null != entityMeta.getIdStrategy() && null != entityMeta.getIdGenerator()) {
        int bizIdLength = entityMeta.getBizIdLength();
        int idLength = entityMeta.getIdLength();
        Object[] rowData;
        Object relatedColValue = null;
        int idJdbcType = entityMeta.getIdType();
        int businessIdType = hasBizId ? entityMeta.getColumnType(entityMeta.getBusinessIdField()) : 0;
        for (int i = 0; i < paramValues.size(); i++) {
            rowData = (Object[]) paramValues.get(i);
            if (relatedColumn != null) {
                relatedColValue = rowData[relatedColumn];
            }
            if (StringUtil.isBlank(rowData[pkIndex])) {
                rowData[pkIndex] = entityMeta.getIdGenerator().getId(entityMeta.getTableName(), signature, relatedColValue, null, idJdbcType, idLength);
                // 回写主键值
                BeanUtils.setProperty(entities.get(i), entityMeta.getIdArray()[0], rowData[pkIndex]);
            }
            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]);
            }
        }
    }
    String saveOrUpdateSql = generateSqlHandler.generateSql(entityMeta, forceUpdateFields);
    if (sqlToyContext.isDebug())
        out.println("saveOrUpdateAll=" + saveOrUpdateSql);
    return SqlUtil.batchUpdateByJdbc(saveOrUpdateSql, paramValues, batchSize, null, entityMeta.getFieldsTypeArray(), autoCommit, conn);
}
Also used : ReflectPropertyHandler(org.sagacity.sqltoy.callback.ReflectPropertyHandler)

Example 14 with ReflectPropertyHandler

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

the class DialectUtils method update.

/**
 * @todo 单笔记录修改
 * @param sqlToyContext
 * @param entity
 * @param entityMeta
 * @param nullFunction
 * @param forceUpdateFields
 * @param conn
 * @param tableName
 * @throws Exception
 */
public static Long update(SqlToyContext sqlToyContext, Serializable entity, EntityMeta entityMeta, String nullFunction, String[] forceUpdateFields, Connection conn, String tableName) throws Exception {
    // 全部是主键则无需update,无主键则同样不符合修改规则
    if (entityMeta.getRejectIdFieldArray() == null || entityMeta.getIdArray() == null) {
        throw new Exception("表:" + entityMeta.getTableName() + " 字段全部是主键或无主键,不符合update规则,请检查表设计是否合理!");
    }
    // 构造全新的修改记录参数赋值反射(覆盖之前的)
    ReflectPropertyHandler handler = getUpdateReflectHandler(sqlToyContext, null);
    Object[] fieldsValues = BeanUtil.reflectBeanToAry(entity, entityMeta.getFieldsArray(), null, handler);
    // 判断主键是否为空
    int pkIndex = entityMeta.getIdIndex();
    for (int i = pkIndex; i < pkIndex + entityMeta.getIdArray().length; i++) {
        if (fieldsValues[i] == null)
            throw new Exception("通过对象进行update操作,主键字段必须要赋值!");
    }
    // 构建update语句
    String updateSql = generateUpdateSql(entityMeta, nullFunction, forceUpdateFields, tableName);
    if (updateSql == null)
        throw new Exception("update sql is null,引起问题的原因是没有设置需要修改的字段!");
    if (sqlToyContext.isDebug())
        out.println("update last execute sql:" + updateSql);
    return executeSql(updateSql, fieldsValues, entityMeta.getFieldsTypeArray(), conn, null);
}
Also used : ReflectPropertyHandler(org.sagacity.sqltoy.callback.ReflectPropertyHandler) SQLException(java.sql.SQLException) IOException(java.io.IOException)

Example 15 with ReflectPropertyHandler

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

the class SybaseIQDialect method update.

/*
	 * (non-Javadoc)
	 * 
	 * @see org.sagacity.sqltoy.dialect.Dialect#update(org.sagacity.sqltoy.
	 * SqlToyContext , java.io.Serializable, java.lang.String[],
	 * java.sql.Connection)
	 */
@Override
public Long update(SqlToyContext sqlToyContext, Serializable entity, String[] forceUpdateFields, final boolean cascade, final Class[] emptyCascadeClasses, final HashMap<Class, String[]> subTableForceUpdateProps, Connection conn, final String tableName) throws Exception {
    EntityMeta entityMeta = sqlToyContext.getEntityMeta(entity.getClass());
    Long updateCount = DialectUtils.update(sqlToyContext, entity, entityMeta, NVL_FUNCTION, forceUpdateFields, conn, tableName);
    // 级联保存
    if (cascade && null != entityMeta.getOneToManys() && !entityMeta.getOneToManys().isEmpty()) {
        HashMap<Type, String> typeMap = new HashMap<Type, String>();
        if (emptyCascadeClasses != null)
            for (Type type : emptyCascadeClasses) {
                typeMap.put(type, "");
            }
        // 级联子表数据
        List subTableData;
        final Object[] IdValues = BeanUtil.reflectBeanToAry(entity, entityMeta.getIdArray(), null, null);
        String[] forceUpdateProps = null;
        for (OneToManyModel oneToMany : entityMeta.getOneToManys()) {
            forceUpdateProps = (subTableForceUpdateProps == null) ? null : subTableForceUpdateProps.get(oneToMany.getMappedType());
            subTableData = (List) BeanUtil.invokeMethod(entity, "get".concat(StringUtil.firstToUpperCase(oneToMany.getProperty())), null);
            final String[] mappedFields = oneToMany.getMappedFields();
            /**
             * 针对子表存量数据,调用级联修改的语句,分delete 和update两种操作 1、删除存量数据;2、设置存量数据状态为停用
             */
            if (oneToMany.getCascadeUpdateSql() != null && ((subTableData != null && !subTableData.isEmpty()) || typeMap.containsKey(oneToMany.getMappedType()))) {
                SqlToyResult sqlToyResult = SqlConfigParseUtils.processSql(oneToMany.getCascadeUpdateSql(), mappedFields, IdValues);
                DialectUtils.executeSql(sqlToyResult.getSql(), sqlToyResult.getParamsValue(), null, conn, null);
            }
            // 子表数据不为空,采取saveOrUpdateAll操作
            if (subTableData != null && !subTableData.isEmpty()) {
                saveOrUpdateAll(sqlToyContext, subTableData, sqlToyContext.getBatchSize(), // 设置关联外键字段的属性值(来自主表的主键)
                new ReflectPropertyHandler() {

                    public void process() {
                        for (int i = 0; i < mappedFields.length; i++) {
                            this.setValue(mappedFields[i], IdValues[i]);
                        }
                    }
                }, forceUpdateProps, conn, null, null);
            }
        }
    }
    return updateCount;
}
Also used : EntityMeta(org.sagacity.sqltoy.config.model.EntityMeta) HashMap(java.util.HashMap) SqlToyResult(org.sagacity.sqltoy.config.model.SqlToyResult) SqlType(org.sagacity.sqltoy.config.model.SqlType) DBType(org.sagacity.sqltoy.utils.DataSourceUtils.DBType) Type(java.lang.reflect.Type) ArrayList(java.util.ArrayList) List(java.util.List) ReflectPropertyHandler(org.sagacity.sqltoy.callback.ReflectPropertyHandler) OneToManyModel(org.sagacity.sqltoy.config.model.OneToManyModel)

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