1. 程式人生 > 程式設計 >MyBatis的動態SQL語句實現

MyBatis的動態SQL語句實現

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>

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。