需求描述:
根据参数变量pid,动态获取各个省份(pid)所属的表,如 pid 为1 则查询的表为 table_1。
具体实现:
1、建立两个测试表 test_1、test_2
DROP TABLE IF EXISTS `test_1`;
CREATE TABLE `test_1` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of test_1
-- ----------------------------
INSERT INTO `test_1` VALUES ('1', '1111');
DROP TABLE IF EXISTS `test_2`;
CREATE TABLE `test_2` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of test_1
-- ----------------------------
INSERT INTO `test_1` VALUES ('1', '2222');
2、实体类test实现 IDynamicTableName 接口,重写 getDynamicTableName 方法
import javax.persistence.*;
/**
* @description: 测试分表实体类
* @author:
* @create:
*/
@Data
@Table(name = "test")
public class Test implements IDynamicTableName {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
@Transient//非数据库字段,不查询
private String pid;
/**
* @description: 动态表名拼接组装方法
* @param:
* @return: java.lang.String
* @author: chenping
* @date: 2020/3/2
**/
@Override
public String getDynamicTableName() {
StringBuffer tableName = new StringBuffer(this.getClass().getAnnotation(Table.class).name());
return tableName+"_"+pid;
}
3、实体类对应的mapper不变:
import tk.mybatis.mapper.common.Mapper;
public interface TestMapper extends Mapper<Test> {
}
4、测试 简单的增删改查:
@RestController
@Log4j2
public class TestController extends BaseController {
@Autowired
TestMapper testMapper;
/**
* @description: 测试分表接口
* @param:
* @return: java.lang.String
* @author:
* @date:
**/
@PostMapping("/test")
public String test() {
Test t = new Test();
t.setPid("2");
List<Test> list = testMapper.select(t);
//
// //insert
// t.setPid("1");
// t.setName("11111114");
// int insert = testMapper.insert(t);
// log.info("insert num:"+insert);
//update
t.setPid("2");
t.setId(1);
t.setName("22222222223");
/**
* 不支持 Example 更新,需要将实体获取的表名set给Example
**/
Example example = new Example(t.getClass());
example.setTableName(t.getDynamicTableName());
Example.Criteria criteria = example.createCriteria();
criteria.andEqualTo("id", 1);
criteria.andEqualTo("name", "22222222221");
// int update = testMapper.updateByExampleSelective(t,example);//不加example.setTableName 不支持
int update = testMapper.updateByExample(t,example);//不加example.setTableName 不支持
// int update = testMapper.updateByPrimaryKey(t);//支持
// int update = testMapper.updateByPrimaryKeySelective(t);//支持
log.info("update num:"+update);
//delete
// t.setPid("1");
// t.setId(3);
// int delete = testMapper.delete(t);
// log.info("delete num:"+delete);
return update+"";
}