项目场景:
简单记录一些Mybatis构造的常用sql写法,仅做为笔记记录,无其他作用。
1.数据插入通过map传参,灵活插入表格数据
<insert id="saveExportRecord">
insert into ${downloadTable}
<foreach collection="recordMap.keys" item="key" open="(" close=")"
separator=",">
${key}
</foreach>
values
<foreach collection="recordMap.values" item="value" open="("
close=")" separator=",">
#{value}
</foreach>
</insert>
2. 构造where条件
List<Map> selectMapsPage(@Param(Constants.WRAPPER) Wrapper query, @Param("tableName") String tableName);
<select id="selectMapsPage" resultType="java.util.Map" parameterType="java.util.Map">
SELECT *
FROM ${tableName}
<if test="ew.emptyOfWhere == false">
${ew.customSqlSegment}
</if>
</select>
3.构造where条件和sql语句where条件混用1
/**
* 根据自定义sql查询
* @param query
* @param tableName
* @param fields
* @param joinCustomSqlSql
* @param orderBySql
* @return
*/
List<Map> selectListByCustomSql(@Param(Constants.WRAPPER) Wrapper query, @Param("tableName") String tableName, @Param("fields") String fields, @Param("joinCustomSqlSql") String joinCustomSqlSql, @Param("orderBySql") String orderBySql);
<select id="selectListByCustomSql" resultType="java.util.Map" parameterType="java.util.Map">
SELECT ${fields}
FROM ${tableName}
<if test="ew.emptyOfWhere == false">
<where>
${joinCustomSqlSql}
<if test="ew.customSqlSegment != null and ew.customSqlSegment.startsWith('WHERE')">
AND
</if>
${ew.sqlSegment}
</where>
</if>
order by ${orderBySql}
</select>
4.构造where条件和sql语句where条件混用2
List<Map> paymentList(@Param(Constants.WRAPPER) Wrapper query, @Param("examId") String examId);
<select id="paymentList" resultType="java.util.Map" parameterType="java.lang.String">
SELECT a.`ORDNO`, a.`ORDAMT`
FROM `exam_${examId}_examinee` a,`exam_config` cg
<if test="ew.emptyOfWhere == false">
<where>
a.SS = cg.department_code
AND cg.examid = #{examId}
<if test="ew.customSqlSegment != null and ew.customSqlSegment.startsWith('WHERE')">
AND
</if>
${ew.sqlSegment}
</where>
</if>
</select>