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