org.jfaster.badger.util.ShardUtils Maven / Gradle / Ivy
The newest version!
package org.jfaster.badger.util;
import java.util.ArrayList;
import java.util.List;
import org.jfaster.badger.Badger;
import org.jfaster.badger.exception.MappingException;
import org.jfaster.badger.query.shard.DataSourceShardStrategy;
import org.jfaster.badger.query.shard.ShardResult;
import org.jfaster.badger.query.shard.ShardTableInfo;
import org.jfaster.badger.query.shard.TableInfo;
import org.jfaster.badger.query.shard.TableShardStrategy;
import org.jfaster.badger.sql.ParseResult;
/**
* 分库分表工具
* @author yanpengfang
* create 2019-01-16 3:31 PM
*/
public class ShardUtils {
public static ShardResult shard(Class> clazz, Object shardValue) {
ShardResult res = new ShardResult();
ShardTableInfo shardInfo = SqlUtils.getShardTableInfo(clazz);
if (shardInfo == null) {
TableInfo tableInfo = SqlUtils.getTableInfo(clazz);
res.setDataSourceName(tableInfo.getDataSourceName());
return res;
}
String shardField = shardInfo.getFieldName();
String fieldName = SqlUtils.getIdFields(clazz).get(0);
if (!fieldName.equals(shardField)) {
throw new MappingException("如果通过id删除,并且带有分库分表信息,则分表字段必须是id");
}
return shard(shardValue, shardInfo, res);
}
public static ShardResult shard(Object o, boolean checkId) {
Class> clazz = o.getClass();
ShardResult res = new ShardResult();
ShardTableInfo shardInfo = SqlUtils.getShardTableInfo(clazz);
if (shardInfo == null) {
TableInfo tableInfo = SqlUtils.getTableInfo(clazz);
res.setDataSourceName(tableInfo.getDataSourceName());
return res;
}
String shardField = shardInfo.getFieldName();
if (checkId) {
String fieldName = SqlUtils.getIdFields(clazz).get(0);
if (!fieldName.equals(shardField)) {
throw new MappingException("如果通过id删除,并且带有分库分表信息,则分表字段必须是id");
}
}
Object shardValue = SqlUtils.getValueByField(o, shardField);
return shard(shardValue, shardInfo, res);
}
public static ShardResult shard(Class> clazz, String condition, List
© 2015 - 2025 Weber Informatics LLC | Privacy Policy