Search in sources :

Example 1 with SavePKStrategy

use of org.sagacity.sqltoy.dialect.model.SavePKStrategy in project sagacity-sqltoy by chenrenfei.

the class MySqlDialect 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 String tableName) throws Exception {
    // mysql只支持identity,sequence 值忽略,mysql identity可以手工插入
    EntityMeta entityMeta = sqlToyContext.getEntityMeta(entity.getClass());
    boolean isAssignPK = isAssignPKValue(entityMeta.getIdStrategy());
    String insertSql = DialectUtils.generateInsertSql(DBType.MYSQL, entityMeta, entityMeta.getIdStrategy(), NVL_FUNCTION, "NEXTVAL FOR " + entityMeta.getSequence(), isAssignPK, tableName);
    ReturnPkType returnPkType = (entityMeta.getIdStrategy() != null && entityMeta.getIdStrategy().equals(PKStrategy.SEQUENCE)) ? ReturnPkType.GENERATED_KEYS : ReturnPkType.PREPARD_ID;
    return DialectUtils.save(sqlToyContext, entityMeta, entityMeta.getIdStrategy(), isAssignPK, returnPkType, insertSql, entity, new GenerateSqlHandler() {

        public String generateSql(EntityMeta entityMeta, String[] forceUpdateField) {
            return DialectUtils.generateInsertSql(DBType.MYSQL, entityMeta, entityMeta.getIdStrategy(), NVL_FUNCTION, "NEXTVAL FOR " + entityMeta.getSequence(), isAssignPKValue(entityMeta.getIdStrategy()), null);
        }
    }, new GenerateSavePKStrategy() {

        public SavePKStrategy generate(EntityMeta entityMeta) {
            return new SavePKStrategy(entityMeta.getIdStrategy(), isAssignPKValue(entityMeta.getIdStrategy()));
        }
    }, conn);
}
Also used : EntityMeta(org.sagacity.sqltoy.config.model.EntityMeta) GenerateSqlHandler(org.sagacity.sqltoy.dialect.handler.GenerateSqlHandler) GenerateSavePKStrategy(org.sagacity.sqltoy.dialect.handler.GenerateSavePKStrategy) ReturnPkType(org.sagacity.sqltoy.dialect.model.ReturnPkType) GenerateSavePKStrategy(org.sagacity.sqltoy.dialect.handler.GenerateSavePKStrategy) SavePKStrategy(org.sagacity.sqltoy.dialect.model.SavePKStrategy)

Example 2 with SavePKStrategy

use of org.sagacity.sqltoy.dialect.model.SavePKStrategy in project sagacity-sqltoy by chenrenfei.

the class SqliteDialect 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 String tableName) throws Exception {
    // sqlite 只提供autoincrement 机制,即identity模式,所以sequence可以忽略
    EntityMeta entityMeta = sqlToyContext.getEntityMeta(entity.getClass());
    boolean isAssignPk = isAssignPKValue(entityMeta.getIdStrategy());
    String insertSql = DialectUtils.generateInsertSql(DBType.SQLITE, entityMeta, entityMeta.getIdStrategy(), NVL_FUNCTION, "NEXTVAL FOR " + entityMeta.getSequence(), isAssignPk, tableName);
    return DialectUtils.save(sqlToyContext, entityMeta, entityMeta.getIdStrategy(), isAssignPk, ReturnPkType.PREPARD_ID, insertSql, entity, new GenerateSqlHandler() {

        public String generateSql(EntityMeta entityMeta, String[] forceUpdateField) {
            return DialectUtils.generateInsertSql(DBType.SQLITE, entityMeta, entityMeta.getIdStrategy(), NVL_FUNCTION, "NEXTVAL FOR " + entityMeta.getSequence(), isAssignPKValue(entityMeta.getIdStrategy()), null);
        }
    }, new GenerateSavePKStrategy() {

        public SavePKStrategy generate(EntityMeta entityMeta) {
            return new SavePKStrategy(entityMeta.getIdStrategy(), isAssignPKValue(entityMeta.getIdStrategy()));
        }
    }, conn);
}
Also used : EntityMeta(org.sagacity.sqltoy.config.model.EntityMeta) GenerateSqlHandler(org.sagacity.sqltoy.dialect.handler.GenerateSqlHandler) GenerateSavePKStrategy(org.sagacity.sqltoy.dialect.handler.GenerateSavePKStrategy) GenerateSavePKStrategy(org.sagacity.sqltoy.dialect.handler.GenerateSavePKStrategy) SavePKStrategy(org.sagacity.sqltoy.dialect.model.SavePKStrategy)

Example 3 with SavePKStrategy

use of org.sagacity.sqltoy.dialect.model.SavePKStrategy 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 SavePKStrategy

use of org.sagacity.sqltoy.dialect.model.SavePKStrategy in project sagacity-sqltoy by chenrenfei.

the class SqliteDialect 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 {
    // sqlite 只提供autoincrement 机制,即identity模式,所以sequence可以忽略
    EntityMeta entityMeta = sqlToyContext.getEntityMeta(entity.getClass());
    boolean isAssignPk = SqliteDialectUtils.isAssignPKValue(entityMeta.getIdStrategy());
    String insertSql = DialectExtUtils.generateInsertSql(dbType, entityMeta, entityMeta.getIdStrategy(), NVL_FUNCTION, "NEXTVAL FOR " + entityMeta.getSequence(), isAssignPk, tableName);
    return DialectUtils.save(sqlToyContext, entityMeta, entityMeta.getIdStrategy(), isAssignPk, ReturnPkType.PREPARD_ID, insertSql, entity, new GenerateSqlHandler() {

        @Override
        public String generateSql(EntityMeta entityMeta, String[] forceUpdateField) {
            return DialectExtUtils.generateInsertSql(dbType, entityMeta, entityMeta.getIdStrategy(), NVL_FUNCTION, "NEXTVAL FOR " + entityMeta.getSequence(), SqliteDialectUtils.isAssignPKValue(entityMeta.getIdStrategy()), null);
        }
    }, new GenerateSavePKStrategy() {

        @Override
        public SavePKStrategy generate(EntityMeta entityMeta) {
            return new SavePKStrategy(entityMeta.getIdStrategy(), SqliteDialectUtils.isAssignPKValue(entityMeta.getIdStrategy()));
        }
    }, 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)

Example 5 with SavePKStrategy

use of org.sagacity.sqltoy.dialect.model.SavePKStrategy in project sagacity-sqltoy by chenrenfei.

the class PostgreSqlDialectUtils method save.

/**
 * @todo 保存单条对象记录
 * @param sqlToyContext
 * @param entity
 * @param conn
 * @param dbType
 * @param tableName
 * @return
 * @throws Exception
 */
public static Object save(SqlToyContext sqlToyContext, Serializable entity, Connection conn, final Integer dbType, String tableName) throws Exception {
    // 只支持sequence模式
    EntityMeta entityMeta = sqlToyContext.getEntityMeta(entity.getClass());
    PKStrategy pkStrategy = entityMeta.getIdStrategy();
    String sequence = "nextval('" + entityMeta.getSequence() + "')";
    // 从10版本开始支持identity
    if (pkStrategy != null && pkStrategy.equals(PKStrategy.IDENTITY)) {
        // 伪造成sequence模式
        pkStrategy = PKStrategy.SEQUENCE;
        sequence = "DEFAULT";
    }
    boolean isAssignPK = isAssignPKValue(pkStrategy);
    String insertSql = DialectExtUtils.generateInsertSql(dbType, entityMeta, pkStrategy, NVL_FUNCTION, sequence, isAssignPK, tableName);
    return DialectUtils.save(sqlToyContext, entityMeta, pkStrategy, isAssignPK, ReturnPkType.GENERATED_KEYS, insertSql, entity, new GenerateSqlHandler() {

        @Override
        public String generateSql(EntityMeta entityMeta, String[] forceUpdateField) {
            PKStrategy pkStrategy = entityMeta.getIdStrategy();
            String sequence = "nextval('" + entityMeta.getSequence() + "')";
            if (pkStrategy != null && pkStrategy.equals(PKStrategy.IDENTITY)) {
                // 伪造成sequence模式
                pkStrategy = PKStrategy.SEQUENCE;
                sequence = "DEFAULT";
            }
            return DialectExtUtils.generateInsertSql(dbType, entityMeta, pkStrategy, NVL_FUNCTION, sequence, isAssignPKValue(pkStrategy), null);
        }
    }, new GenerateSavePKStrategy() {

        @Override
        public SavePKStrategy generate(EntityMeta entityMeta) {
            return new SavePKStrategy(entityMeta.getIdStrategy(), isAssignPKValue(entityMeta.getIdStrategy()));
        }
    }, conn, dbType);
}
Also used : EntityMeta(org.sagacity.sqltoy.config.model.EntityMeta) GenerateSqlHandler(org.sagacity.sqltoy.callback.GenerateSqlHandler) GenerateSavePKStrategy(org.sagacity.sqltoy.callback.GenerateSavePKStrategy) GenerateSavePKStrategy(org.sagacity.sqltoy.callback.GenerateSavePKStrategy) SavePKStrategy(org.sagacity.sqltoy.dialect.model.SavePKStrategy) PKStrategy(org.sagacity.sqltoy.config.model.PKStrategy) GenerateSavePKStrategy(org.sagacity.sqltoy.callback.GenerateSavePKStrategy) SavePKStrategy(org.sagacity.sqltoy.dialect.model.SavePKStrategy)

Aggregations

EntityMeta (org.sagacity.sqltoy.config.model.EntityMeta)19 SavePKStrategy (org.sagacity.sqltoy.dialect.model.SavePKStrategy)19 GenerateSavePKStrategy (org.sagacity.sqltoy.callback.GenerateSavePKStrategy)12 GenerateSqlHandler (org.sagacity.sqltoy.callback.GenerateSqlHandler)11 PKStrategy (org.sagacity.sqltoy.config.model.PKStrategy)8 GenerateSavePKStrategy (org.sagacity.sqltoy.dialect.handler.GenerateSavePKStrategy)7 ReturnPkType (org.sagacity.sqltoy.dialect.model.ReturnPkType)7 GenerateSqlHandler (org.sagacity.sqltoy.dialect.handler.GenerateSqlHandler)6 IOException (java.io.IOException)2 PreparedStatement (java.sql.PreparedStatement)2 ResultSet (java.sql.ResultSet)2 SQLException (java.sql.SQLException)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 PreparedStatementResultHandler (org.sagacity.sqltoy.callback.PreparedStatementResultHandler)2 ReflectPropertyHandler (org.sagacity.sqltoy.callback.ReflectPropertyHandler)1 ReflectPropsHandler (org.sagacity.sqltoy.callback.ReflectPropsHandler)1 OneToManyModel (org.sagacity.sqltoy.config.model.OneToManyModel)1 TableCascadeModel (org.sagacity.sqltoy.config.model.TableCascadeModel)1