1.if where
实现一个简单的需求:
根据性别和名字查询用户:
正常来写:
<select id="selectUserBySexAndUsername" parameterType="pojo.User" resultType="pojo.User"> select * from user where sex = #{sex} and username = #{username} </select>
弊端:传入参数user必须要有性别和姓名,缺一不可
于是我稍做修改:
<select id="selectUserBySexAndUsername" parameterType="pojo.User" resultType="pojo.User"> select * from user where <if test="sex != null and sex != ''"> sex = #{sex} </if> <if test="username != null and username != ''"> and username = #{username} </if> </select>
看似可以了,但是,如果sex不存在而username存在,SQL语句错误
这时候,只需要加入一个Where标签即可:
<select id="selectUserBySexAndUsername" parameterType="pojo.User" resultType="pojo.User"> select * from user <where> <if test="sex != null and sex != ''"> sex = #{sex} </if> <if test="username != null and username != ''"> and username = #{username} </if> </where> </select>
现在就可以满足需求了,只要至少存在一个条件即可查询成功
2.SQL片段:
很多的SQL标签内SQL语句重复,那么我们可以提出来共用吗?
可以:
<sql id="selector"> select * from user </sql> <select id="selectUser"> <include refid="selector" /> <where> <if test="sex != null and sex != ''"> sex = #{sex} </if> <if test="username != null and username != ''"> and username = #{username} </if> </where> </select>
这种设计思想值得学习,不过实际开发种并不会使用
3.foreach
情景:根据多个ID查询用户:
先写个包装类,里面有一个存用户ID的List
(先展示包装类的方法是因为直接用数组或者List会有坑,下边会解释)
package pojo; import java.io.Serializable; import java.util.List; public class QueryVo implements Serializable { private static final long serialVersionUID = 1L;private List<Integer> idsList;public List<Integer> getIdsList() { return idsList; } public void setIdsList(List<Integer> idsList) { this.idsList = idsList; } }
查询:
<select id="selectUserByIds" parameterType="pojo.QueryVo" resultType="pojo.User"> select * from user <where> <foreach collection="idsList" item="id" separator="," open="id in (" close=")"> #{id} </foreach> </where> </select>
不过这里要特别注意:如果foreach循环的不是List集合,而是简单的数组:
collection不能写成属性名(如这里的idsList),而是要写成array
因此可见,如果我们foreach循环的不是包装类属性,而直接是List集合,
Collection也应该写成list。