if 標籤
一、持久層接口
public interface IUserDao {
List<User> findUsers(User user);
}
二、持久層接口映射文件
<mapper namespace="chu.yi.bo.dao.IUserDao">
<select id="findUsers" resultType="chu.yi.bo.domain.User" parameterType="chu.yi.bo.domain.User">
select * from user where 1=1
<if test="username != null and username != ''">
and username like '%${username}%'
</if>
<if test="sex != null and sex != ''">
and sex = #{sex}
</if>
</select>
</mapper>
注意:if 標籤的 test 屬性可以使用 OGNL 表達式
三、查詢操作
User u = new User();
// 賦值操作
u.set...;
List<User> users = userDao.findUsers(u);
where 標籤
一、持久層接口
public interface IUserDao {
List<User> findUsers(User user);
}
二、持久層接口映射文件
<mapper namespace="chu.yi.bo.dao.IUserDao">
<select id="findUsers" resultType="chu.yi.bo.domain.User" parameterType="chu.yi.bo.domain.User">
select * from user
<where>
<if test="username!=null and username != ''">
and username like '%${username}%'
</if>
<if test="sex != null and sex != ''">
and sex = #{sex}
</if>
</where>
</select>
</mapper>
三、查詢操作
User u = new User();
// 賦值操作
u.set...;
// 執行操作
List<User> users = userDao.findUsers(u);
foreach 標籤使用
一、創建包裝類
public class QueryVo {
private List<Integer> ids;
......
}
二、持久層接口
public interface IUserDao {
List<User> findInIds(QueryVo vo);
}
三、持久層接口映射文件
<mapper namespace="chu.yi.bo.dao.IUserDao">
<select id="findInIds" resultType="chu.yi.bo.domain.User" parameterType="chu.yi.bo.domain.QueryVo">
select * from user
<where>
<if test="ids != null and ids.size() > 0">
<foreach collection="ids" open="id in ( " close=")" item="id" separator=",">
#{id}
</foreach>
</if>
</where>
</select>
</mapper>
- collection :代表要遍歷的集合元素,注意編寫時不要寫 #{}
- open :代表語句的開始部分
- close :代表結束部分
- item :代表遍歷集合的每個元素,生成的變量名
- sperator :代表分隔符
四、查詢操作
QueryVo vo = new QueryVo();
List<Integer> ids = new ArrayList<Integer>();
// 添加查詢數據
ids.add;
...
vo.setIds(ids);
//6.執行操作
List<User> users = userDao.findInIds(vo);
SQL 片段
將重複的 sql 提取出來,使用 include 引用,達到 sql 重用的目的。
<!-- 抽取重複的語句代碼片段 -->
<sql id="defaultSql">
select * from user
</sql>
<!-- 根據 id 查詢 -->
<select id="findById" resultType="UsEr" parameterType="int">
<include refid="defaultSql"/>
where id = #{id}
</select>