Search in sources :

Example 71 with EntityMeta

use of org.sagacity.sqltoy.config.model.EntityMeta in project sagacity-sqltoy by chenrenfei.

the class DMDialect method save.

/*
	 * (non-Javadoc)
	 * 
	 * @see org.sagacity.sqltoy.dialect.Dialect#save(org.sagacity.sqltoy.
	 * SqlToyContext , java.io.Serializable, java.util.List, java.sql.Connection)
	 */
@Override
public Object save(SqlToyContext sqlToyContext, Serializable entity, Connection conn, final Integer dbType, final String dialect, final String tableName) throws Exception {
    EntityMeta entityMeta = sqlToyContext.getEntityMeta(entity.getClass());
    PKStrategy pkStrategy = entityMeta.getIdStrategy();
    String sequence = entityMeta.getSequence().concat(".nextval");
    if (pkStrategy != null && pkStrategy.equals(PKStrategy.IDENTITY)) {
        pkStrategy = PKStrategy.SEQUENCE;
        sequence = entityMeta.getFieldsMeta().get(entityMeta.getIdArray()[0]).getDefaultValue();
    }
    boolean isAssignPK = DMDialectUtils.isAssignPKValue(pkStrategy);
    String insertSql = DialectExtUtils.generateInsertSql(dbType, entityMeta, pkStrategy, NVL_FUNCTION, sequence, isAssignPK, tableName);
    return DialectUtils.save(sqlToyContext, entityMeta, pkStrategy, isAssignPK, ReturnPkType.PREPARD_ID, insertSql, entity, new GenerateSqlHandler() {

        @Override
        public String generateSql(EntityMeta entityMeta, String[] forceUpdateField) {
            PKStrategy pkStrategy = entityMeta.getIdStrategy();
            String sequence = entityMeta.getSequence().concat(".nextval");
            if (pkStrategy != null && pkStrategy.equals(PKStrategy.IDENTITY)) {
                pkStrategy = PKStrategy.SEQUENCE;
                sequence = entityMeta.getFieldsMeta().get(entityMeta.getIdArray()[0]).getDefaultValue();
            }
            return DialectExtUtils.generateInsertSql(dbType, entityMeta, pkStrategy, NVL_FUNCTION, sequence, DMDialectUtils.isAssignPKValue(pkStrategy), null);
        }
    }, new GenerateSavePKStrategy() {

        @Override
        public SavePKStrategy generate(EntityMeta entityMeta) {
            PKStrategy pkStrategy = entityMeta.getIdStrategy();
            if (pkStrategy != null && pkStrategy.equals(PKStrategy.IDENTITY)) {
                pkStrategy = PKStrategy.SEQUENCE;
            }
            return new SavePKStrategy(pkStrategy, DMDialectUtils.isAssignPKValue(pkStrategy));
        }
    }, conn, dbType);
}
Also used : EntityMeta(org.sagacity.sqltoy.config.model.EntityMeta) GenerateSqlHandler(org.sagacity.sqltoy.callback.GenerateSqlHandler) GenerateSavePKStrategy(org.sagacity.sqltoy.callback.GenerateSavePKStrategy) SavePKStrategy(org.sagacity.sqltoy.dialect.model.SavePKStrategy) GenerateSavePKStrategy(org.sagacity.sqltoy.callback.GenerateSavePKStrategy) PKStrategy(org.sagacity.sqltoy.config.model.PKStrategy) SavePKStrategy(org.sagacity.sqltoy.dialect.model.SavePKStrategy) GenerateSavePKStrategy(org.sagacity.sqltoy.callback.GenerateSavePKStrategy)

Example 72 with EntityMeta

use of org.sagacity.sqltoy.config.model.EntityMeta in project sagacity-sqltoy by chenrenfei.

the class SqlToyDaoSupport method generateBizId.

/**
 * @todo 产生业务ID
 * @param entityClass
 * @param bizDate
 * @return
 * @throws Exception
 */
protected String generateBizId(Class entityClass, Date bizDate) throws Exception {
    EntityMeta entityMeta = this.getEntityMeta(entityClass);
    if (entityMeta == null || entityMeta.getBusinessIdGenerator() == null)
        throw new Exception(StringUtil.fillArgs("对象:{},没有配置业务主键生成策略,请检查POJO 的业务主键配置!", entityClass.getName()));
    int businessIdType = entityMeta.getColumnType(entityMeta.getBusinessIdField());
    return entityMeta.getBusinessIdGenerator().getId(entityMeta.getTableName(), entityMeta.getBizIdSignature(), null, bizDate, businessIdType, entityMeta.getBizIdLength()).toString();
}
Also used : EntityMeta(org.sagacity.sqltoy.config.model.EntityMeta)

Example 73 with EntityMeta

use of org.sagacity.sqltoy.config.model.EntityMeta 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 74 with EntityMeta

use of org.sagacity.sqltoy.config.model.EntityMeta in project sagacity-sqltoy by chenrenfei.

the class PostgreSqlDialectUtils method saveAll.

/**
 * @todo 批量保存对象入数据库
 * @param sqlToyContext
 * @param entities
 * @param batchSize
 * @param reflectPropertyHandler
 * @param conn
 * @param autoCommit
 * @param tableName
 * @throws Exception
 */
public static Long saveAll(SqlToyContext sqlToyContext, List<?> entities, final int batchSize, ReflectPropertyHandler reflectPropertyHandler, Connection conn, final Boolean autoCommit, String tableName) throws Exception {
    EntityMeta entityMeta = sqlToyContext.getEntityMeta(entities.get(0).getClass());
    PKStrategy pkStrategy = entityMeta.getIdStrategy();
    String sequence = "nextval('" + entityMeta.getSequence() + "')";
    if (pkStrategy != null && pkStrategy.equals(PKStrategy.IDENTITY)) {
        pkStrategy = PKStrategy.SEQUENCE;
        sequence = "nextval(" + entityMeta.getFieldsMeta().get(entityMeta.getIdArray()[0]).getDefaultValue() + ")";
    }
    boolean isAssignPK = isAssignPKValue(pkStrategy);
    String insertSql = DialectUtils.generateInsertSql(DBType.POSTGRESQL, entityMeta, pkStrategy, NVL_FUNCTION, sequence, isAssignPK, tableName);
    return DialectUtils.saveAll(sqlToyContext, entityMeta, pkStrategy, isAssignPK, insertSql, entities, batchSize, reflectPropertyHandler, conn, autoCommit);
}
Also used : EntityMeta(org.sagacity.sqltoy.config.model.EntityMeta) GenerateSavePKStrategy(org.sagacity.sqltoy.dialect.handler.GenerateSavePKStrategy) SavePKStrategy(org.sagacity.sqltoy.dialect.model.SavePKStrategy) PKStrategy(org.sagacity.sqltoy.config.model.PKStrategy)

Example 75 with EntityMeta

use of org.sagacity.sqltoy.config.model.EntityMeta 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)

Aggregations

EntityMeta (org.sagacity.sqltoy.config.model.EntityMeta)141 SavePKStrategy (org.sagacity.sqltoy.dialect.model.SavePKStrategy)36 PKStrategy (org.sagacity.sqltoy.config.model.PKStrategy)28 GenerateSavePKStrategy (org.sagacity.sqltoy.callback.GenerateSavePKStrategy)24 ArrayList (java.util.ArrayList)23 Serializable (java.io.Serializable)22 SqlToyConfig (org.sagacity.sqltoy.config.model.SqlToyConfig)22 List (java.util.List)20 GenerateSqlHandler (org.sagacity.sqltoy.callback.GenerateSqlHandler)20 GenerateSqlHandler (org.sagacity.sqltoy.dialect.handler.GenerateSqlHandler)13 GenerateSavePKStrategy (org.sagacity.sqltoy.dialect.handler.GenerateSavePKStrategy)12 IOException (java.io.IOException)11 SQLException (java.sql.SQLException)11 HashMap (java.util.HashMap)11 TableCascadeModel (org.sagacity.sqltoy.config.model.TableCascadeModel)10 ReturnPkType (org.sagacity.sqltoy.dialect.model.ReturnPkType)10 OneToManyModel (org.sagacity.sqltoy.config.model.OneToManyModel)8 SqlToyResult (org.sagacity.sqltoy.config.model.SqlToyResult)8 Type (java.lang.reflect.Type)6 PreparedStatement (java.sql.PreparedStatement)6