Search in sources :

Example 6 with ReflectPropertyHandler

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

the class SapIQDialectUtils method saveAll.

/**
 * @todo 保存批量对象数据
 * @param sqlToyContext
 * @param entityMeta
 * @param pkStrategy
 * @param isAssignPK
 * @param insertSql
 * @param entities
 * @param reflectPropertyHandler
 * @param conn
 * @throws Exception
 */
private static Long saveAll(SqlToyContext sqlToyContext, EntityMeta entityMeta, PKStrategy pkStrategy, boolean isAssignPK, String insertSql, List<?> entities, final int batchSize, ReflectPropertyHandler reflectPropertyHandler, Connection conn) 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);
    if (entityMeta.isHasDefaultValue())
        return SqlUtilsExt.batchUpdateByJdbc(insertSql, paramValues, batchSize, entityMeta, null, conn);
    else
        return SqlUtilsExt.batchUpdateByJdbc(insertSql, paramValues, batchSize, entityMeta.getFieldsTypeArray(), null, conn);
}
Also used : ArrayList(java.util.ArrayList) ReflectPropertyHandler(org.sagacity.sqltoy.callback.ReflectPropertyHandler)

Example 7 with ReflectPropertyHandler

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

the class SqlToyCRUDServiceTest method testSaveOrUpdateAll.

@Test
public void testSaveOrUpdateAll() {
    List entities = new ArrayList();
    DictTypeVO dictTypeVO = new DictTypeVO();
    dictTypeVO.setDictTypeCode("POST_TYPE");
    dictTypeVO.setDictTypeName("岗位类别更新");
    // dictTypeVO.setOperateDate(DateUtil.getNowTime());
    // dictTypeVO.setOperator("admin");
    dictTypeVO.setDataType(0);
    dictTypeVO.setStatus("1");
    entities.add(dictTypeVO);
    DictTypeVO dictTypeVO1 = new DictTypeVO();
    dictTypeVO1.setDictTypeCode("POST_TYPE2");
    dictTypeVO1.setDictTypeName("岗位类别2");
    // dictTypeVO1.setOperateDate(DateUtil.getNowTime());
    // dictTypeVO1.setOperator("admin");
    dictTypeVO1.setDataType(0);
    dictTypeVO1.setStatus("1");
    entities.add(dictTypeVO1);
    sqlToyCRUDService.saveOrUpdateAll(entities, null, new ReflectPropertyHandler() {

        @Override
        public void process() {
            this.setValue("status", "2");
        }
    });
}
Also used : DictTypeVO(sqltoy.showcase.sagacity.vo.DictTypeVO) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) ReflectPropertyHandler(org.sagacity.sqltoy.callback.ReflectPropertyHandler) Test(org.junit.Test)

Example 8 with ReflectPropertyHandler

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

the class SqlServerDialectUtils method save.

/**
 * @todo 保存对象
 * @param sqlToyContext
 * @param entity
 * @param conn
 * @param dbType
 * @return
 * @throws Exception
 */
public static Object save(SqlToyContext sqlToyContext, Serializable entity, final Connection conn, final Integer dbType) throws Exception {
    EntityMeta entityMeta = sqlToyContext.getEntityMeta(entity.getClass());
    final boolean isIdentity = entityMeta.getIdStrategy() != null && entityMeta.getIdStrategy().equals(PKStrategy.IDENTITY);
    final boolean isSequence = entityMeta.getIdStrategy() != null && entityMeta.getIdStrategy().equals(PKStrategy.SEQUENCE);
    String insertSql = generateInsertSql(dbType, entityMeta, entityMeta.getIdStrategy(), "isnull", "@mySeqVariable", isIdentity ? false : true);
    if (isSequence)
        insertSql = "set nocount on DECLARE @mySeqVariable as numeric(20)=NEXT VALUE FOR " + entityMeta.getSequence() + " " + insertSql + " select @mySeqVariable ";
    // 无主键,或多主键且非identity、sequence模式
    boolean noPK = (entityMeta.getIdArray() == null);
    int pkIndex = entityMeta.getIdIndex();
    ReflectPropertyHandler handler = DialectUtils.getAddReflectHandler(sqlToyContext, null);
    Object[] fullParamValues = BeanUtil.reflectBeanToAry(entity, (isIdentity) ? entityMeta.getRejectIdFieldArray() : entityMeta.getFieldsArray(), null, handler);
    boolean needUpdatePk = false;
    // 是否存在业务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 idLength = entityMeta.getIdLength();
        int bizIdLength = entityMeta.getBizIdLength();
        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]);
        }
    }
    final Object[] paramValues = fullParamValues;
    final Integer[] paramsType = entityMeta.getFieldsTypeArray();
    // sqlserver2012 开始默认为false
    boolean openIdentity = SqlToyConstants.sqlServerIdentityOpen();
    if (isIdentity && openIdentity)
        DialectUtils.executeSql("SET IDENTITY_INSERT " + entityMeta.getSchemaTable() + " ON", null, null, conn, true);
    if (sqlToyContext.isDebug())
        out.println(insertSql);
    final String realInsertSql = insertSql;
    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)
                pst = conn.prepareStatement(realInsertSql, PreparedStatement.RETURN_GENERATED_KEYS);
            else
                pst = conn.prepareStatement(realInsertSql);
            if (null != paramValues && paramValues.length > 0) {
                int index = 0;
                for (int i = 0, n = paramValues.length; i < n; i++) {
                    if (!paramsType[i].equals(java.sql.Types.TIMESTAMP)) {
                        SqlUtil.setParamValue(conn, pst, paramValues[i], paramsType[i], index + 1);
                        index++;
                    }
                }
            }
            ResultSet keyResult = null;
            if (isSequence)
                keyResult = pst.executeQuery();
            else
                pst.execute();
            if (isIdentity)
                keyResult = pst.getGeneratedKeys();
            if (isSequence || isIdentity) {
                while (keyResult.next()) this.setResult(keyResult.getObject(1));
            }
        }
    });
    // 无主键直接返回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);
            for (OneToManyModel oneToMany : entityMeta.getOneToManys()) {
                final String[] mappedFields = oneToMany.getMappedFields();
                subTableData = (List) PropertyUtils.getProperty(entity, oneToMany.getProperty());
                if (subTableData != null && !subTableData.isEmpty()) {
                    saveAll(sqlToyContext, subTableData, new ReflectPropertyHandler() {

                        public void process() {
                            for (int i = 0; i < mappedFields.length; i++) {
                                this.setValue(mappedFields[i], idValues[i]);
                            }
                        }
                    }, conn, dbType, null);
                }
            }
        }
        if (isIdentity && openIdentity)
            DialectUtils.executeSql("SET IDENTITY_INSERT " + entityMeta.getSchemaTable() + " OFF", null, null, conn, true);
        return result;
    }
}
Also used : EntityMeta(org.sagacity.sqltoy.config.model.EntityMeta) SQLException(java.sql.SQLException) PreparedStatementResultHandler(org.sagacity.sqltoy.callback.PreparedStatementResultHandler) PreparedStatement(java.sql.PreparedStatement) IOException(java.io.IOException) ResultSet(java.sql.ResultSet) ArrayList(java.util.ArrayList) List(java.util.List) ReflectPropertyHandler(org.sagacity.sqltoy.callback.ReflectPropertyHandler) OneToManyModel(org.sagacity.sqltoy.config.model.OneToManyModel)

Example 9 with ReflectPropertyHandler

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

the class SapIQDialectUtils method save.

/**
 * @todo 保存对象(sybase iq支持sequence)
 * @param sqlToyContext
 * @param entity
 * @param openIdentity
 * @param conn
 * @param tableName
 * @return
 * @throws Exception
 */
public static Object save(SqlToyContext sqlToyContext, Serializable entity, boolean openIdentity, final Connection conn, String tableName) throws Exception {
    final EntityMeta entityMeta = sqlToyContext.getEntityMeta(entity.getClass());
    final boolean isIdentity = entityMeta.getIdStrategy() != null && entityMeta.getIdStrategy().equals(PKStrategy.IDENTITY);
    final boolean isSequence = entityMeta.getIdStrategy() != null && entityMeta.getIdStrategy().equals(PKStrategy.SEQUENCE);
    String insertSql = DialectUtils.generateInsertSql(DBType.SYBASE_IQ, entityMeta, entityMeta.getIdStrategy(), null, "@mySeqVariable", false, tableName);
    if (isSequence)
        insertSql = "set nocount on DECLARE @mySeqVariable decimal(20) select @mySeqVariable=" + entityMeta.getSequence() + ".NEXTVAL " + insertSql + " select @mySeqVariable ";
    // 无主键,或多主键且非identity、sequence模式
    boolean noPK = (entityMeta.getIdArray() == null);
    int pkIndex = entityMeta.getIdIndex();
    Object[] fullParamValues = BeanUtil.reflectBeanToAry(entity, (isIdentity || isSequence) ? entityMeta.getRejectIdFieldArray() : entityMeta.getFieldsArray(), null, null);
    boolean needUpdatePk = false;
    // 是否存在业务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 idLength = entityMeta.getIdLength();
        int bizIdLength = entityMeta.getBizIdLength();
        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]);
        }
    }
    final Object[] paramValues = fullParamValues;
    final Integer[] paramsType = entityMeta.getFieldsTypeArray();
    if (isIdentity)
        insertSql = insertSql + " select @@IDENTITY ";
    if (sqlToyContext.isDebug())
        out.println(insertSql);
    final String realInsertSql = insertSql;
    PreparedStatement pst = null;
    Object result = SqlUtil.preparedStatementProcess(null, pst, null, new PreparedStatementResultHandler() {

        public void execute(Object obj, PreparedStatement pst, ResultSet rs) throws SQLException, IOException {
            pst = conn.prepareStatement(realInsertSql);
            // 存在默认值
            if (entityMeta.isHasDefaultValue())
                SqlUtilsExt.setParamsValue(conn, pst, paramValues, entityMeta);
            else
                SqlUtil.setParamsValue(conn, pst, paramValues, paramsType, 0);
            ResultSet keyResult = null;
            if (isSequence || isIdentity)
                keyResult = pst.executeQuery();
            else
                pst.execute();
            if (isSequence || isIdentity) {
                while (keyResult.next()) this.setResult(keyResult.getObject(1));
            }
        }
    });
    // 无主键直接返回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);
            for (OneToManyModel oneToMany : entityMeta.getOneToManys()) {
                final String[] mappedFields = oneToMany.getMappedFields();
                subTableData = (List) PropertyUtils.getProperty(entity, oneToMany.getProperty());
                if (subTableData != null && !subTableData.isEmpty()) {
                    saveAll(sqlToyContext, subTableData, sqlToyContext.getBatchSize(), new ReflectPropertyHandler() {

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

Example 10 with ReflectPropertyHandler

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

the class DialectUtils method getUpdateReflectHandler.

/**
 * @todo 构造修改记录参数反射赋值处理器
 * @param sqlToyContext
 * @param preHandler
 * @return
 */
public static ReflectPropertyHandler getUpdateReflectHandler(SqlToyContext sqlToyContext, final ReflectPropertyHandler preHandler) {
    if (sqlToyContext.getUnifyFieldsHandler() == null)
        return preHandler;
    final Map<String, Object> keyValues = sqlToyContext.getUnifyFieldsHandler().updateUnifyFields();
    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)

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