Spring Boot中Mybatis實戰經驗
【分表處理】
mybatis-generator-core.jar自動生成的dao裡面只有針對原表的操作,若要處理分表,需特殊處理,以下總結二種方案。1. 使用Map方式
1)xml中的parameterType="map" statementType="STATEMENT"
2)呼叫方傳入的map中包括分表名,xml中使用${分表名},例如:
map.put("subTable","USER_INFO")
xml中使用 INSERT INTO ${subTable}
3)動態SQL使用:
<if test="_parameter.containsKey('userName')">
AND msgType = ${userName})
</if>
2. 使用javaBean方式
1)model層自動生成的javaBean類中需定義分表名屬性,例如: subTable,並提供setter,getter方法
2)xml中的parameterType="javaBean類",表名使用${subTable}
3)針對selectByPrimaryKey等入參只有1個Integer或String的簡單資料型別,無法通過javaBean傳入分表名,此時通過@param繫結變數,例如:
UserInfoMapper.java中
UserInfo selectByPrimaryKey(@Param("subTable") String subTable,@Param("userId") Integer userId);
UserInfoMapper.xml中
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
-->
select
<include refid="Base_Column_List" />
from ${subTable}
where USER_ID = #{userId,jdbcType=INTEGER}
</select>
【特殊符號處理】
由於在xml中不能有>或<等符號,需特殊處理:
方法一
使用轉義符替換,例如:
<if test="beginTime != null" >
AND CREATE_TIME >= DATE_FORMAT('${beginTime}','%Y-%m-%d %H:%i:%S')
</if>
附:XML轉義字元
< < 小於號
> > 大於號
& & 和
' ’ 單引號
" " 雙引號
方法二
使用<![CDATA[ ]]>,例如:
<if test="beginTime != null" >
<![CDATA[ AND CREATE_TIME >= DATE_FORMAT('${beginTime}','%Y-%m-%d %H:%i:%S') ]]>
</if>