use of org.sagacity.sqltoy.config.annotation.Sharding in project sagacity-sqltoy by chenrenfei.
the class EntityManager method parseSharding.
/**
* @todo 解析分库分表策略
* @param entityMeta
* @param entityClass
*/
private void parseSharding(EntityMeta entityMeta, Class entityClass) {
Class classType = entityClass;
Sharding sharding = null;
// 增加递归对父类检测
while (classType != null && !classType.equals(Object.class)) {
sharding = (Sharding) classType.getAnnotation(Sharding.class);
if (sharding != null) {
break;
}
classType = classType.getSuperclass();
}
// 不存在分库策略
if (sharding == null) {
return;
}
// 分库策略
ShardingConfig shardingConfig = new ShardingConfig();
// 最大并行数量
shardingConfig.setMaxConcurrents(sharding.maxConcurrents());
// 最大执行时长(秒)
shardingConfig.setMaxWaitSeconds(sharding.maxWaitSeconds());
// 异常处理策略(是否全局回滚)
shardingConfig.setGlobalRollback(sharding.is_global_rollback());
Strategy shardingDB = sharding.db();
String strategy = shardingDB.name();
// 分库策略
if (StringUtil.isNotBlank(strategy)) {
ShardingStrategyConfig config = new ShardingStrategyConfig(0);
config.setFields(shardingDB.fields());
// 别名,如果没有设置则将fields作为默认别名,别名的目的在于共用sharding策略中的参数名称
String[] aliasNames = new String[shardingDB.fields().length];
System.arraycopy(shardingDB.fields(), 0, aliasNames, 0, aliasNames.length);
if (shardingDB.aliasNames() != null) {
System.arraycopy(shardingDB.aliasNames(), 0, aliasNames, 0, shardingDB.aliasNames().length);
}
config.setAliasNames(aliasNames);
config.setDecisionType(shardingDB.decisionType());
config.setStrategy(strategy);
shardingConfig.setShardingDBStrategy(config);
}
// 分表策略
Strategy shardingTable = sharding.table();
strategy = shardingTable.name();
if (StringUtil.isNotBlank(strategy)) {
ShardingStrategyConfig config = new ShardingStrategyConfig(1);
config.setFields(shardingTable.fields());
// 别名,如果没有设置则将fields作为默认别名,别名的目的在于共用sharding策略中的参数名称
String[] aliasNames = new String[shardingTable.fields().length];
System.arraycopy(shardingTable.fields(), 0, aliasNames, 0, aliasNames.length);
if (shardingTable.aliasNames() != null) {
System.arraycopy(shardingTable.aliasNames(), 0, aliasNames, 0, shardingTable.aliasNames().length);
}
config.setTables(new String[] { entityMeta.getTableName() });
config.setAliasNames(aliasNames);
config.setDecisionType(shardingDB.decisionType());
config.setStrategy(strategy);
shardingConfig.setShardingTableStrategy(config);
}
// 必须有一个策略是存在的
if (shardingConfig.getShardingDBStrategy() != null || shardingConfig.getShardingTableStrategy() != null) {
entityMeta.setShardingConfig(shardingConfig);
}
}
Aggregations