Fork me on GitHub

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

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 字段只能使用 ${},而不能使用 #{}

 

posted @   龙凌云端  阅读(1880)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示