mybatis核心 对sql语句进行灵活操作,通过表达式进行判断,对sql进行灵活拼接、组装。
可以使用if,sql片段,或是foreach
具体代码如下:
(UserMapper.xml)
<!--在sql片段中不要包括where-->
<sql id="query_user_where">
<if test="forumPostUser!=null">
<if test="forumPostUser.loginName!=null and forumPostUser.loginName!=''">
AND oa_user.loginName = #{forumPostUser.loginName}
</if>
<if test="forumPostUser.name!=null and forumPostUser.name!=''">
AND oa_user.name LIKE '%${forumPostUser.name}%'
</if>
<if test="ids!=null">
<!-- 使用foreach遍历传入ids-->
<!-- collection:指定输入对象集合属性-->
<!-- item:每个遍历生成对象-->
<!-- open:开始遍历时拼接的串-->
<!-- close:结束遍历时拼接的串-->
<!-- separator:遍历的两个对象中需要拼接的串-->
<!-- AND (id=100 OR id =101 OR id =102)-->
<foreach collection="ids" item="id" open="AND (" close=")" separator="or">
id = #{id}
</foreach>
</if>
</if>
</sql>
<!--发帖用户信息综合查询-->
<select id="findUserList" parameterType="com.mybatis.po.TopicQueryVo" resultType="com.mybatis.po.ForumPostUser">
<!-- SELECT * FROM oa_user WHERE oa_user.loginName = #{forumPostUser.loginName}-->
<!-- AND oa_user.name LIKE '%${forumPostUser.name}%'-->
<!-- 将上面的sql语句改写成动态Sql-->
SELECT * FROM oa_user
<!-- where可以自动去掉条件中的第一个and-->
<where>
<!--<if test="forumPostUser!=null">-->
<!--<if test="forumPostUser.loginName!=null and forumPostUser.loginName!=''">-->
<!--AND oa_user.loginName = #{forumPostUser.loginName}-->
<!--</if>-->
<!--<if test="forumPostUser.name!=null and forumPostUser.name!=''">-->
<!--AND oa_user.name LIKE '%${forumPostUser.name}%'-->
<!--</if>-->
<!--</if>-->
<!-- 引用sql片段,如果引用的id不在本mapper文件中,需要前边加namespace-->
<include refid="query_user_where"/>
<!-- 在这里还要引用其他的sql片段-->
</where>
</select>