use of org.sagacity.sqltoy.config.model.OneToManyModel in project sagacity-sqltoy by chenrenfei.
the class DialectUtils method load.
/**
* @todo 加载获取单笔数据库记录
* @param sqlToyContext
* @param sqlToyConfig
* @param sql
* @param entityMeta
* @param entity
* @param cascadeTypes
* @param conn
* @return
* @throws Exception
*/
public static Serializable load(final SqlToyContext sqlToyContext, SqlToyConfig sqlToyConfig, String sql, EntityMeta entityMeta, Serializable entity, List<Class> cascadeTypes, Connection conn) throws Exception {
Object[] pkValues = BeanUtil.reflectBeanToAry(entity, entityMeta.getIdArray(), null, null);
for (int i = 0; i < pkValues.length; i++) if (null == pkValues[i])
throw new Exception("load method must assign value for pk,null pk field is:" + entityMeta.getIdArray()[i]);
SqlToyResult sqlToyResult = SqlConfigParseUtils.processSql(sql, entityMeta.getIdArray(), pkValues);
// 显示sql
SqlExecuteStat.showSql(sqlToyResult.getSql(), sqlToyResult.getParamsValue());
QueryResult queryResult = findBySql(sqlToyContext, sqlToyConfig, sqlToyResult.getSql(), sqlToyResult.getParamsValue(), null, conn, 0, -1, -1);
List rows = queryResult.getRows();
Serializable result = null;
if (rows != null && rows.size() > 0) {
rows = BeanUtil.reflectListToBean(rows, ResultUtils.humpFieldNames(queryResult.getLabelNames()), entity.getClass());
result = (Serializable) rows.get(0);
}
if (result == null)
return null;
// 存在主表对应子表
if (null != cascadeTypes && !cascadeTypes.isEmpty() && !entityMeta.getOneToManys().isEmpty()) {
List pkRefDetails;
for (OneToManyModel oneToMany : entityMeta.getOneToManys()) {
// 判定是否要加载
if (cascadeTypes.contains(oneToMany.getMappedType())) {
sqlToyResult = SqlConfigParseUtils.processSql(oneToMany.getLoadSubTableSql(), oneToMany.getMappedFields(), pkValues);
if (sqlToyContext.isDebug())
out.println("auto load sub table dataSet sql:".concat(sqlToyResult.getSql()));
pkRefDetails = SqlUtil.findByJdbcQuery(sqlToyResult.getSql(), sqlToyResult.getParamsValue(), oneToMany.getMappedType(), null, conn);
if (null != pkRefDetails)
BeanUtils.setProperty(result, oneToMany.getProperty(), pkRefDetails);
}
}
}
return result;
}
use of org.sagacity.sqltoy.config.model.OneToManyModel 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.OneToManyModel 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.OneToManyModel 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);
}
use of org.sagacity.sqltoy.config.model.OneToManyModel 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;
}
}
Aggregations