1. Background
In some business scenarios, the table needs to be divided into tables (for example: divide the table by day, test_20220123, test_20220124).
After splitting the table, how to dynamically pass in the table name to the split table to insert and query data?
Two, the solution
1. Create entity
1)DbTable.java
Base class: There is only one field, tableName, which is used to pass in the name of the data table.
public class DbTable {
private String tableName;
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
}
2) TestTable.java
Test class: contains id, name two fields.
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. Add & query data
1) Business logic
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 file
List<TestTable> testDynamicTableName(TestTable testTable);
int insertDynamicTableName(TestTable testTable);
3) mapper.xml file
<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>
[ Note ] The tableName field here can only use ${} , not #{}