MyBatis 插入和查询动态表名中的数据

一、背景说明

有些业务场景,需要对表进行了分表操作(如:按天分表,test_20220123,test_20220124)。

分表后,如何对分表进行动态传入表名,进行插入和查询数据呢?


二、解决方案

1、创建实体

1)DbTable.java

基类:只有 tableName 一个字段,用于传入数据表名。

public class DbTable {
    
    
    private String tableName;

    public String getTableName() {
    
    
        return tableName;
    }

    public void setTableName(String tableName) {
    
    
        this.tableName = tableName;
    }
}
2)TestTable.java

测试类:包含 id,name 两个字段。

public class TestTable extends DbTable {
    
    
    private Integer id;
    private String name;

    public Integer getId() {
    
    
        return id;
    }

    public void setId(Integer id) {
    
    
        this.id = id;
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    @Override
    public String toString() {
    
    
        return "TestTable{" +
                "tableName='" + super.getTableName() + '\'' +
                ", id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

2、新增&查询数据

1)业务逻辑
		String tableName = "test_20220124"; // 动态传入表名
        TestTable testTable = new TestTable();
        testTable.setTableName(tableName);
        testTable.setId(7);
        testTable.setName("d");
        final int insert = otherResourceMapper.insertDynamicTableName(testTable);
        System.out.println("insert: " + insert);
        List<TestTable> list = otherResourceMapper.testDynamicTableName(testTable);
        System.out.println("tableName: " + tableName + ", list size: " + list.size());
2)mapper.java 文件
    List<TestTable> testDynamicTableName(TestTable testTable);
    int insertDynamicTableName(TestTable testTable);
3)mapper.xml 文件
<select id="testDynamicTableName" parameterType="com.manage.model.TestTable" resultType="com.manage.model.TestTable">
        select * from ${
    
    tableName}
    </select>

    <insert id="insertDynamicTableName" parameterType="com.manage.model.TestTable">
        insert into ${
    
    tableName}(id, name)
        values (#{
    
    id}, #{
    
    name})
    </insert>

注意】此处的 tableName 字段只能使用 ${},而不能使用 #{}


猜你喜欢

转载自blog.csdn.net/aikudexiaohai/article/details/131368805