use of org.sagacity.sqltoy.config.model.EntityMeta in project sagacity-sqltoy by chenrenfei.
the class OracleDialect method saveAll.
/*
* (non-Javadoc)
*
* @see org.sagacity.sqltoy.dialect.Dialect#saveAll(org.sagacity.sqltoy.
* SqlToyContext , java.util.List,
* org.sagacity.core.utils.callback.ReflectPropertyHandler, java.sql.Connection)
*/
@Override
public Long saveAll(SqlToyContext sqlToyContext, List<?> entities, final int batchSize, ReflectPropertyHandler reflectPropertyHandler, Connection conn, final Boolean autoCommit, final String tableName) throws Exception {
// oracle12c 开始支持identity机制
EntityMeta entityMeta = sqlToyContext.getEntityMeta(entities.get(0).getClass());
PKStrategy pkStrategy = entityMeta.getIdStrategy();
String sequence = entityMeta.getSequence() + NEXTVAL;
if (pkStrategy != null && pkStrategy.equals(PKStrategy.IDENTITY)) {
pkStrategy = PKStrategy.SEQUENCE;
sequence = entityMeta.getFieldsMeta().get(entityMeta.getIdArray()[0]).getDefaultValue();
}
String insertSql = DialectUtils.generateInsertSql(DBType.ORACLE, entityMeta, pkStrategy, NVL_FUNCTION, sequence, isAssignPKValue(pkStrategy), tableName);
return DialectUtils.saveAll(sqlToyContext, entityMeta, pkStrategy, isAssignPKValue(pkStrategy), insertSql, entities, batchSize, reflectPropertyHandler, conn, autoCommit);
}
use of org.sagacity.sqltoy.config.model.EntityMeta 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);
}
use of org.sagacity.sqltoy.config.model.EntityMeta 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;
}
}
use of org.sagacity.sqltoy.config.model.EntityMeta in project sagacity-sqltoy by chenrenfei.
the class DialectUtils method delete.
/**
* @todo 删除单个对象以及其级联表数据
* @param sqlToyContext
* @param entity
* @param conn
* @param tableName
* @throws Exception
*/
public static Long delete(SqlToyContext sqlToyContext, Serializable entity, Connection conn, final String tableName) throws Exception {
if (entity == null)
return new Long(0);
EntityMeta entityMeta = sqlToyContext.getEntityMeta(entity.getClass());
if (null == entityMeta.getIdArray())
throw new Exception("delete 操作,表:" + entityMeta.getSchemaTable() + "没有主键,请检查表设计!");
Object[] idValues = BeanUtil.reflectBeanToAry(entity, entityMeta.getIdArray(), null, null);
Integer[] parameterTypes = new Integer[idValues.length];
boolean validator = true;
for (int i = 0, n = idValues.length; i < n; i++) {
parameterTypes[i] = entityMeta.getColumnType(entityMeta.getIdArray()[i]);
if (null == idValues[i]) {
validator = false;
break;
}
}
if (!validator) {
throw new IllegalAccessException("delete operate is illegal,table must has primary key and all primaryKey's value must has value!");
}
// 级联删除子表数据
if (!entityMeta.getOneToManys().isEmpty()) {
for (OneToManyModel oneToMany : entityMeta.getOneToManys()) {
// 如果数据库本身通过on delete cascade机制,则sqltoy无需进行删除操作
if (oneToMany.isDelete()) {
if (sqlToyContext.isDebug())
out.println("cascade delete sub table sql:".concat(oneToMany.getDeleteSubTableSql()));
executeSql(oneToMany.getDeleteSubTableSql(), idValues, parameterTypes, conn, null);
}
}
}
if (sqlToyContext.isDebug())
out.println(entityMeta.getDeleteByIdsSql(tableName));
return executeSql(entityMeta.getDeleteByIdsSql(tableName), idValues, parameterTypes, conn, null);
}
use of org.sagacity.sqltoy.config.model.EntityMeta in project sagacity-sqltoy by chenrenfei.
the class DialectUtils method deleteAll.
/**
* @todo 批量删除对象并级联删除掉子表数据
* @param sqlToyContext
* @param entities
* @param batchSize
* @param conn
* @param autoCommit
* @param tableName
* @throws Exception
*/
public static Long deleteAll(SqlToyContext sqlToyContext, List<?> entities, final int batchSize, Connection conn, final Boolean autoCommit, final String tableName) throws Exception {
if (null == entities || entities.isEmpty())
return new Long(0);
EntityMeta entityMeta = sqlToyContext.getEntityMeta(entities.get(0).getClass());
if (null == entityMeta.getIdArray())
throw new Exception("delete/deleteAll 操作,表:" + entityMeta.getSchemaTable() + "没有主键,请检查表设计!");
List<Object[]> idValues = BeanUtil.reflectBeansToInnerAry(entities, entityMeta.getIdArray(), null, null, false, 0);
// 判断主键值是否存在空
Object[] idsValue;
for (int i = 0, n = idValues.size(); i < n; i++) {
idsValue = idValues.get(i);
for (Object obj : idsValue) if (StringUtil.isBlank(obj))
throw new Exception("第[" + i + "]行数据主键值存在空,批量删除以主键为依据,主键不能为空!");
}
int idsLength = entityMeta.getIdArray().length;
Integer[] parameterTypes = new Integer[idsLength];
for (int i = 0, n = idsLength; i < n; i++) parameterTypes[i] = entityMeta.getColumnType(entityMeta.getIdArray()[i]);
// 级联批量删除子表数据
if (!entityMeta.getOneToManys().isEmpty()) {
for (OneToManyModel oneToMany : entityMeta.getOneToManys()) {
// 如果数据库本身通过on delete cascade机制,则sqltoy无需进行删除操作
if (oneToMany.isDelete()) {
if (sqlToyContext.isDebug())
out.println("cascade batch delete sub table sql:".concat(oneToMany.getDeleteSubTableSql()));
SqlUtilsExt.batchUpdateByJdbc(oneToMany.getDeleteSubTableSql(), idValues, sqlToyContext.getBatchSize(), parameterTypes, null, conn);
}
}
}
if (sqlToyContext.isDebug())
out.println(entityMeta.getDeleteByIdsSql(tableName));
return SqlUtilsExt.batchUpdateByJdbc(entityMeta.getDeleteByIdsSql(tableName), idValues, batchSize, parameterTypes, autoCommit, conn);
}
Aggregations