驽马十驾 驽马十驾

驽马十驾,功在不舍

目录
MyBatis的几个小技巧
/  

MyBatis的几个小技巧

前言

最近没有怎么更新博客,我有罪!
最近用MyBatis做ORM层,所以记录下一些新的知识。

Like查询

官方推荐的做法是使用bind

<if test="condition.hospitalName != null and condition.hospitalName!= ''">
		<bind name="pattern" value="'%' + condition.hospitalName + '%'"/>
		and e.hospital_name like #{pattern,jdbcType=VARCHAR}
</if>

字符串判定

可以通过如下表达式进行更严格的判定

<if test="condition.title != null and condition.title != ''">
	and e.title = #{condition.title,jdbcType=VARCHAR}
</if>

list判定

<if test="condition.adeptIdList != null and condition.adeptIdList.size() != 0">
</if>

活学活用的foreach

业务中有几个and也有几个or条件,大概的sql如下

SELECT *
 FROM exp_expert e
 INNER JOIN exp_expert_adept ea
 ON e.id = ea.expert_id
 WHERE e.as_delete = 0 AND e.expert_name LIKE '%expert%' AND e.title = 'title' AND (ea.adept_id = 1 OR ea.adept_id = 2 OR ea.adept_id = 3);

最后的OR添加如此写:

<if test="condition.adeptIdList != null and condition.adeptIdList.size() != 0">
	and
			<foreach item="item" index="index" collection="condition.adeptIdList"
					open="(" separator="or" close=")">
					ea.adept_id = #{item}
			</foreach>
	</if>

活学活用了separator

完了

总结完成,完结撒花!

最后推荐一个插件:MyBatisCodeHelper,功能用起来太爽了。

骐骥一跃,不能十步。驽马十驾,功在不舍。