MyBatis动态传表名,字段名

时间:2021-12-05 01:37:47

要实现动态传入表名、列名,需要做如下修改
添加属性statementType=”STATEMENT”
同时sql里的属有变量取值都改成${xxxx},而不是#{xxx}

<mapper namespace="com.vip.collection.biz.repository.collection.DeleteDataByBatchDayRepository" >
<resultMap id="BaseResultMap" type="com.vip.collection.biz.data.entity.RawDataNo" >
<result column="minId" property="minId" />
<result column="maxId" property="maxId" />
</resultMap>

<select id="selectRawId" resultMap="BaseResultMap" statementType="STATEMENT">
select min(${primaryKeyColumnName}) as minId, max(${primaryKeyColumnName}) as maxId from ${table} where 1=1 and ${columnName} = '${batchDate}'
</select>
  1. statementType:STATEMENT(非预编译),PREPARED(预编译)或CALLABLE中的任意一个,这就告诉 MyBatis 分别使用Statement,PreparedStatement或者CallableStatement。默认:PREPARED。这里显然不能使用预编译,要改成非预编译。

  2. xxxx 将传入的数据直接显示生成在sql中,对于字符串数据,需要手动加上引号。
    [java] view plain copy
    String dateStr = DateFormatUtils.format(date.getTime(), “yyyy-MM-dd HH:mm:ss”);
    dateStr = “’” + dateStr + “’”;

3.也可以不手动打上引号
在XML文件中配置。日期格式问题mysql有DATE_FORMAT(date,format)函数
参考: MYSQL教程

 <delete id="deleteDataBasedOnDate" statementType="STATEMENT">
delete from ${table}
where <![CDATA[ DATE_FORMAT(${columnName},'%Y-%m-%d') = '${batchDate}' ]]> and ${primaryKeyColumnName} between ${beginningId} and ${endingId}
</delete>