今天写一个根据筛选条件查询三个表中的数据的功能,以前都是会写几个功能在业务层进行判断传进来参数的有无后调用相应的方法,今天同事让我用动态sql,用了一下果然省了很多功夫。动态sql是mybatis其中一个强大特性,它对比数据连接池(JDBC)的话方便得多。
以下是原代码,只是其中一个接口,本来写了like来做模糊查询,结果发现integer类型的不可以,所以如果不用动态sql单纯静态查询的话需要写8个方法。用动态sql后一个就行了。
原代码:
<select id="findCityIdByUsername" resultType="com.indechy.nyj.bean.BusinessSwitch">
SELECT
t_user_enterprises.competentAuthority t_user_enterprises.competent_authority,
t_user_enterprises.username,
t_user_enterprises.leadingLevel t_user_enterprises.leading_level,
batch.bacth,
history.timeOfSubmission history.time_of_submission
FROM
history,t_user_enterprises,batch
WHERE
history.eid=t_user_enterprises.id
AND
history.batch_id=batch.id
AND
history.time_of_submission like CONCAT(CONCAT('%',#{age} ,'%'))
AND
history.record_type like CONCAT(CONCAT('%',#{recordType} ,'%'))
AND
batch.bacth like CONCAT(CONCAT('%',#{bacth} ,'%'))
AND
t_user_enterprises.competent_authority like CONCAT(CONCAT('%',#{competentAuthority},'%'))
AND
t_user_enterprises.leading_level like CONCAT(CONCAT('%',#{leadingLevel} ,'%'))
AND
t_user_enterprises.username like CONCAT(CONCAT('%',#{username} ,'%'))
AND
history.time_of_submission>= #{startTimeOfSubmission}
AND
history.time_of_submission<= #{endTimeOfSubmission}
GROUP BY
t_user_enterprises.username
</select>
修改后的动态sql代码:
<select id="findCityIdByUsername" resultType="com.indechy.nyj.bean.BusinessSwitch">
SELECT
t_user_enterprises.competent_authority competentAuthority,
t_user_enterprises.username username,
t_user_enterprises.leading_level leadingLevel,
batch.bacth bacth,
history.time_of_submission timeofsubmission,
history.record_type recordType
FROM
history,t_user_enterprises,batch
<where>
AND
history.eid=t_user_enterprises.id
AND
history.batch_id=batch.id
<if test="age != null">
AND history.time_of_submission like CONCAT(CONCAT('%',#{age} ,'%'))
</if>
<if test="recordType != null">
AND history.record_type = #{recordType}
</if>
<if test="bacth != null">
AND batch.bacth = #{bacth}
</if>
<if test="competentAuthority != null">
AND t_user_enterprises.competent_authority = #{competentAuthority}
</if>
<if test="leadingLevel != null">
AND t_user_enterprises.leading_level = #{leadingLevel}
</if>
<if test="username != null">
AND t_user_enterprises.username = #{username}
</if>
<if test="startTimeOfSubmission != null">
AND history.time_of_submission >= #{startTimeOfSubmission}
</if>
<if test="endTimeOfSubmission != null">
AND history.time_of_submission <= #{endTimeOfSubmission}
</if>
<if test="recordType != null">
GROUP BY
t_user_enterprises.username
</if>
ORDER BY
history.time_of_submission
DESC
</where>
</select>
这样写的话一个方法就能解决业务需求,第一次运用记录一下,后几天会认真学习一下动态sql的具体内容后再写出来。