use of org.sagacity.sqltoy.config.model.EntityMeta in project sagacity-sqltoy by chenrenfei.
the class DialectUtils method isUnique.
/**
* @todo 进行唯一性查询判定
* @param sqlToyContext
* @param entity
* @param paramsNamed
* @param conn
* @param tableName
* @return
*/
public static boolean isUnique(SqlToyContext sqlToyContext, Serializable entity, final String[] paramsNamed, Connection conn, String tableName) {
try {
EntityMeta entityMeta = sqlToyContext.getEntityMeta(entity.getClass());
String[] realParamNamed;
Object[] paramValues;
int rejectIdFieldsSize = (entityMeta.getRejectIdFieldArray() == null) ? 0 : entityMeta.getRejectIdFieldArray().length;
// 如果没有特别指定属性,则通过数据是否为null来判断具体的字段
if (paramsNamed == null || paramsNamed.length == 0) {
String[] fieldsArray = entityMeta.getFieldsArray();
Object[] fieldValues = BeanUtil.reflectBeanToAry(entity, fieldsArray, null, null);
List paramValueList = new ArrayList();
List<String> paramNames = new ArrayList<String>();
boolean hasNoPkField = false;
for (int i = 0; i < fieldValues.length; i++) {
if (null != fieldValues[i]) {
// 非主键字段
if (i < rejectIdFieldsSize)
hasNoPkField = true;
// 存在主键字段,则主键值仅仅作为返回结果的比较,判断是否是记录本身
if (i >= rejectIdFieldsSize && hasNoPkField)
break;
paramNames.add(fieldsArray[i]);
paramValueList.add(fieldValues[i]);
}
}
paramValues = paramValueList.toArray();
realParamNamed = paramNames.toArray(new String[paramNames.size()]);
} else {
realParamNamed = paramsNamed;
paramValues = BeanUtil.reflectBeanToAry(entity, paramsNamed, null, null);
}
// 构造查询语句
StringBuilder queryStr = new StringBuilder("select 1");
// 如果存在主键,则查询主键字段
if (null != entityMeta.getIdArray()) {
for (String idFieldName : entityMeta.getIdArray()) {
queryStr.append(",");
queryStr.append(entityMeta.getColumnName(idFieldName));
}
}
queryStr.append(" from ");
queryStr.append(StringUtil.isBlank(tableName) ? entityMeta.getSchemaTable() : tableName);
queryStr.append(" where ");
for (int i = 0; i < realParamNamed.length; i++) {
if (i > 0)
queryStr.append(" and ");
queryStr.append(entityMeta.getColumnName(realParamNamed[i])).append("=? ");
}
// 防止数据量过大,先用count方式查询提升效率
long recordCnt = getCountBySql(sqlToyContext, queryStr.toString(), paramValues, true, conn);
if (recordCnt == 0)
return true;
else if (recordCnt > 1)
return false;
SqlExecuteStat.showSql(queryStr.toString(), paramValues);
List result = SqlUtil.findByJdbcQuery(queryStr.toString(), paramValues, null, null, conn);
if (result.size() == 0)
return true;
else if (result.size() > 1)
return false;
// 表没有主键,单条记录算重复
if (null == entityMeta.getIdArray())
return false;
boolean allPK = false;
// 判断是否是主键字段的唯一性验证
if (realParamNamed.length == entityMeta.getIdArray().length) {
allPK = true;
for (String field : realParamNamed) {
if (!entityMeta.getFieldMeta(field).isPK()) {
allPK = false;
break;
}
}
}
// 针对主键字段的唯一性验证,查询有记录则表示主键已经存在
if (allPK)
return false;
// 判断是否是本身
Object[] idValues = BeanUtil.reflectBeanToAry(entity, entityMeta.getIdArray(), null, null);
List compareValues = (List) result.get(0);
// 相等表示唯一
boolean isEqual = true;
for (int i = 0, n = idValues.length; i < n; i++) {
// result 第一列数据为固定的1(select 1,pk1,pk2模式),因此compareValues(i+1);
if (null == idValues[i] || null == compareValues.get(i + 1) || !idValues[i].toString().equals(compareValues.get(i + 1).toString())) {
isEqual = false;
break;
}
}
return isEqual;
} catch (Exception e) {
logger.error("执行唯一性查询失败:{}", e.getMessage());
e.printStackTrace();
}
return false;
}
use of org.sagacity.sqltoy.config.model.EntityMeta in project sagacity-sqltoy by chenrenfei.
the class SybaseIQDialect method saveOrUpdateAll.
/*
* (non-Javadoc)
*
* @see org.sagacity.sqltoy.dialect.Dialect#saveOrUpdateAll(org.sagacity.sqltoy
* .SqlToyContext, java.util.List, java.sql.Connection)
*/
@Override
public Long saveOrUpdateAll(SqlToyContext sqlToyContext, List<?> entities, final int batchSize, final ReflectPropertyHandler reflectPropertyHandler, final String[] forceUpdateFields, Connection conn, final Boolean autoCommit, final String tableName) throws Exception {
EntityMeta entityMeta = sqlToyContext.getEntityMeta(entities.get(0).getClass());
// sybase iq 只支持identity模式
boolean isIdentity = (entityMeta.getIdStrategy() != null && entityMeta.getIdStrategy().equals(PKStrategy.IDENTITY));
boolean isOpenIdentity = (isIdentity && SqlToyConstants.sybaseIQIdentityOpen());
if (isOpenIdentity)
DialectUtils.executeSql("SET TEMPORARY OPTION IDENTITY_INSERT='" + entityMeta.getSchemaTable() + "'", null, null, conn, true);
Long updateCount = DialectUtils.saveOrUpdateAll(sqlToyContext, entities, batchSize, entityMeta, forceUpdateFields, new GenerateSqlHandler() {
public String generateSql(EntityMeta entityMeta, String[] forceUpdateFields) {
return DialectUtils.getSaveOrUpdateSql(DBType.SYBASE_IQ, entityMeta, entityMeta.getIdStrategy(), forceUpdateFields, null, NVL_FUNCTION, entityMeta.getSequence() + ".NEXTVAL", isAssignPKValue(entityMeta.getIdStrategy()), tableName);
}
}, reflectPropertyHandler, conn, autoCommit);
if (isOpenIdentity)
DialectUtils.executeSql("SET TEMPORARY OPTION IDENTITY_INSERT=''", null, null, conn, true);
return updateCount;
}
use of org.sagacity.sqltoy.config.model.EntityMeta in project sagacity-sqltoy by chenrenfei.
the class SybaseIQDialect method saveAllIgnoreExist.
/*
* (non-Javadoc)
*
* @see org.sagacity.sqltoy.dialect.Dialect#saveAllNotExist(org.sagacity.sqltoy.
* SqlToyContext, java.util.List,
* org.sagacity.sqltoy.callback.ReflectPropertyHandler, java.sql.Connection,
* java.lang.Boolean)
*/
@Override
public Long saveAllIgnoreExist(SqlToyContext sqlToyContext, List<?> entities, final int batchSize, ReflectPropertyHandler reflectPropertyHandler, Connection conn, final Boolean autoCommit, final String tableName) throws Exception {
EntityMeta entityMeta = sqlToyContext.getEntityMeta(entities.get(0).getClass());
// sybase iq 只支持identity模式
boolean isIdentity = (entityMeta.getIdStrategy() != null && entityMeta.getIdStrategy().equals(PKStrategy.IDENTITY));
boolean isOpenIdentity = (isIdentity && SqlToyConstants.sybaseIQIdentityOpen());
if (isOpenIdentity)
DialectUtils.executeSql("SET TEMPORARY OPTION IDENTITY_INSERT='" + entityMeta.getSchemaTable() + "'", null, null, conn, true);
Long updateCount = DialectUtils.saveAllIgnoreExist(sqlToyContext, entities, batchSize, entityMeta, new GenerateSqlHandler() {
public String generateSql(EntityMeta entityMeta, String[] forceUpdateFields) {
return DialectUtils.getSaveIgnoreExistSql(DBType.SYBASE_IQ, entityMeta, entityMeta.getIdStrategy(), null, NVL_FUNCTION, entityMeta.getSequence() + ".NEXTVAL", isAssignPKValue(entityMeta.getIdStrategy()), tableName);
}
}, reflectPropertyHandler, conn, autoCommit);
if (isOpenIdentity)
DialectUtils.executeSql("SET TEMPORARY OPTION IDENTITY_INSERT=''", null, null, conn, true);
return updateCount;
}
use of org.sagacity.sqltoy.config.model.EntityMeta in project sagacity-sqltoy by chenrenfei.
the class SybaseIQDialect method load.
/*
* sybase iq 没有所谓的行锁
*
* @see org.sagacity.sqltoy.dialect.Dialect#load(java.io.Serializable,
* java.util.List, java.sql.Connection)
*/
@Override
public Serializable load(final SqlToyContext sqlToyContext, Serializable entity, List<Class> cascadeTypes, LockMode lockMode, Connection conn, final String tableName) throws Exception {
EntityMeta entityMeta = sqlToyContext.getEntityMeta(entity.getClass());
// 获取loadsql(loadsql 可以通过@loadSql进行改变,所以需要sqltoyContext重新获取)
SqlToyConfig sqlToyConfig = sqlToyContext.getSqlToyConfig(entityMeta.getLoadSql(tableName), SqlType.search);
return (Serializable) DialectUtils.load(sqlToyContext, sqlToyConfig, sqlToyConfig.getSql(), entityMeta, entity, cascadeTypes, conn);
}
use of org.sagacity.sqltoy.config.model.EntityMeta in project sagacity-sqltoy by chenrenfei.
the class SybaseIQDialect method update.
/*
* (non-Javadoc)
*
* @see org.sagacity.sqltoy.dialect.Dialect#update(org.sagacity.sqltoy.
* SqlToyContext , java.io.Serializable, java.lang.String[],
* java.sql.Connection)
*/
@Override
public Long update(SqlToyContext sqlToyContext, Serializable entity, String[] forceUpdateFields, final boolean cascade, final Class[] emptyCascadeClasses, final HashMap<Class, String[]> subTableForceUpdateProps, Connection conn, final String tableName) throws Exception {
EntityMeta entityMeta = sqlToyContext.getEntityMeta(entity.getClass());
Long updateCount = DialectUtils.update(sqlToyContext, entity, entityMeta, NVL_FUNCTION, forceUpdateFields, conn, tableName);
// 级联保存
if (cascade && null != entityMeta.getOneToManys() && !entityMeta.getOneToManys().isEmpty()) {
HashMap<Type, String> typeMap = new HashMap<Type, String>();
if (emptyCascadeClasses != null)
for (Type type : emptyCascadeClasses) {
typeMap.put(type, "");
}
// 级联子表数据
List subTableData;
final Object[] IdValues = BeanUtil.reflectBeanToAry(entity, entityMeta.getIdArray(), null, null);
String[] forceUpdateProps = null;
for (OneToManyModel oneToMany : entityMeta.getOneToManys()) {
forceUpdateProps = (subTableForceUpdateProps == null) ? null : subTableForceUpdateProps.get(oneToMany.getMappedType());
subTableData = (List) BeanUtil.invokeMethod(entity, "get".concat(StringUtil.firstToUpperCase(oneToMany.getProperty())), null);
final String[] mappedFields = oneToMany.getMappedFields();
/**
* 针对子表存量数据,调用级联修改的语句,分delete 和update两种操作 1、删除存量数据;2、设置存量数据状态为停用
*/
if (oneToMany.getCascadeUpdateSql() != null && ((subTableData != null && !subTableData.isEmpty()) || typeMap.containsKey(oneToMany.getMappedType()))) {
SqlToyResult sqlToyResult = SqlConfigParseUtils.processSql(oneToMany.getCascadeUpdateSql(), mappedFields, IdValues);
DialectUtils.executeSql(sqlToyResult.getSql(), sqlToyResult.getParamsValue(), null, conn, null);
}
// 子表数据不为空,采取saveOrUpdateAll操作
if (subTableData != null && !subTableData.isEmpty()) {
saveOrUpdateAll(sqlToyContext, subTableData, sqlToyContext.getBatchSize(), // 设置关联外键字段的属性值(来自主表的主键)
new ReflectPropertyHandler() {
public void process() {
for (int i = 0; i < mappedFields.length; i++) {
this.setValue(mappedFields[i], IdValues[i]);
}
}
}, forceUpdateProps, conn, null, null);
}
}
}
return updateCount;
}
Aggregations