MyBatis Dynamic Table Query Guide

Dynamic table name query in MyBatis can be achieved by utilizing the dynamic SQL feature of MyBatis. The specific implementation method is as follows:

  1. Define a method in the Mapper interface that takes a parameter as a dynamic argument for the table name.
public interface YourMapper {
    List<YourDataType> selectDataByTableName(@Param("tableName") String tableName);
}
  1. Choose
  2. At what time?
<select id="selectDataByTableName" resultType="YourDataType">
    SELECT * FROM
    <choose>
        <when test="tableName == 'table1'">
            table1
        </when>
        <when test="tableName == 'table2'">
            table2
        </when>
    </choose>
</select>
  1. When calling the Mapper interface method, pass in the specific table name parameter.
YourMapper yourMapper = sqlSession.getMapper(YourMapper.class);
List<YourDataType> data = yourMapper.selectDataByTableName("table1");

By following the above steps, you can achieve the functionality of querying data based on dynamic table names in MyBatis.

bannerAds