动态SQL
Mybatis核心就是对SQL语句进行灵活的操作,通过表达式进行判断,对SQL进行灵活拼接,组装。
SQL语句:
<select id="findUsersQuery"parameterType="usersquery"
resultType="usersquery">
select
*from users
<where>
<if test="users!=null">
<if test="users.id!=nulland users.id=''">
users.id=#{users.id}
</if>
<iftest="users.username!=null and users.username=''">
users.username like'%${users.username}%'
</if>
</if>
</where>
</select>
SQL片段:将上面实现的动态SQL判断代码块抽取出来,方便程序员开发。
<!-- 定义SQL片段
id:表示SQL片段的唯一标识
经验:是基于单表来定义SQL片段,这样SQL片段的可重用性才高,在SQL片段中不要包括where
-->
<sql id="users_requirements">
<iftest="users!=null">
<iftest="users.id!=null and users.id=''">
users.id=#{users.id}
</if>
<iftest="users.username!=null and users.username=''">
users.usernamelike '%${users.username}%'
</if>
</if>
</sql>
<select id="findUsersQuery"parameterType="usersquery" resultType="usersquery">
Select* from users
<where>
<!-- 引用SQL片段的id,如果refid指定的id不在本mapper文件中,就在前面加上namespace-->
<include refid="users_requirements"></include>
</where>
</select>
Foreach:
Select * from users where id=1 or id=2or id=3;
//传入多个id
private List<Integer> ids;
<!—使用foreach遍历传入ids
Collection:指定输入对象中集合属性
Item:每个遍历生成对象中
Open:开始遍历时拼接串
Close:结束遍历时拼接的串
Separator:遍历的两个对象中需要拼接的串
要实现下面的SQL拼接
And (id=1 or id=10 or id=16)-->
<foreach collection=”ids” item=”user_id”open=”and (” close=”)” separator=”or”>
<!—每次遍历需要拼接的串-->
Id=#{ user_id }
</foreach>