1. 動態SQL之<if>標簽
我們根據實體類的不同取值,使用不同的SQL語句來進行查詢。比如在id如果不為空時可以根據id查詢,如果username不為空時還要加入用戶名作為條件,這種情況在我們的多條件組合查詢中經常會碰到。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.joker.dao.IUserDao">
<select id="findByUser" resultType="user" parameterType="user">
select * from user where 1=1
<if test="username!=null and username != '' ">
and username like #{username}
</if>
<if test="address != null">
and address like #{address}
</if>
</select>
</mapper>
注意:<if>標簽的test屬性中寫的是對象的屬性名,如果是包裝類的對象要使用OGNL表達式的寫法。另外要注意where 1=1的作用。
2. 動態SQL之<where>標簽
為了簡化上面where 1=1的條件拼裝,我們可以采用<where>標簽來簡化開發。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.joker.dao.IUserDao">
<select id="findByUser" resultType="user" parameterType="user">
select * from user
<where>
<if test="username!=null and username != '' ">
and username like #{username}
</if>
<if test="address != null">
and address like #{address}
</if>
</where>
</select>
</mapper>
3. 動態SQL之<foreach>標簽
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.joker.dao.IUserDao">
<!-- 查詢所有用戶在 id的集合之中
foreach標簽:用于遍歷集合
* collection:代表要遍歷的集合元素,注意編寫時不要寫 #{}
* open:代表語句的開始部分
* close:代表結束部分
* item:代表遍歷集合的每個元素,生成的變量名
* sperator:代表分隔符
-->
<select id="findInIds" resultType="user" parameterType="queryvo">
select * from user
<where>
<if test="ids != null and ids.size() > 0">
<foreach collection="ids" open="id in ( " close=")" item="uid" separator=",">
#{uid}
</foreach>
</if>
</where>
</select>
</mapper>
4. MyBatis中的SQL片段
MyBatis的sql中可將重復的sql提取出來,使用時用include引用即可,最終達到sql重用的目的。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.joker.dao.IUserDao">
<!-- 抽取重復的語句代碼片段 -->
<sql id="defaultSql">
select * from user
</sql>
<select id="findAll" resultType="user">
<include refid="defaultSql"></include>
</select>
<select id="findById" resultType="User" parameterType="int">
<include refid="defaultSql"></include>
where id = #{uid}
</select>
</mapper>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。