Mybatis之動態sql

在mybatis中,它提供了一些動態sql標籤,可以讓程序員更快的進行mybatis的開發,這些動態sql可以通過sql的可重用性。。

常用的動態sql標籤:if標籤、where標籤、sql片段、foreach標籤

If標籤/where標籤

<select id="findByMap" parameterType="map" resultType="com.tf.domain.Users">
    select * from users
    <where> 
       <if test="name!=null and name!='' ">
       and name like #{name}
       </if>
       <if test="password!=null and password!='' ">
       and password=#{password}
       </if>
    </where>
    </select>

測試類

Map<String,Object> map = new HashMap<String,Object>();
    map.put("name", "coco");
    map.put("password", "admin");
   List<Users> list = usersMapper.findByMap(map);
for (Users users : list) {
	System.out.println(users);
}

Sql片段

Sql片段可以讓代碼有更高的可重用性

Sql片段需要先定義後使用

比如:上面的代碼修改爲

<!-- 抽取sql片斷 -->
    <sql id="whereClass">
     <where> 
       <if test="name!=null and name!='' ">
       and name like #{name}
       </if>
       <if test="password!=null and password!='' ">
       and password=#{password}
       </if>
    </where>
    </sql>
    <select id="findByMap" parameterType="map" resultType="com.tf.domain.Users">
    select * from users
     <include refid="whereClass"></include>
    </select>

 foreach標籤

可變參數 查詢:SELECT * FROM users WHERE id IN (2,4,5)

 <select id="findByIds" parameterType="list" resultType="com.tf.domain.Users"> 
    select * from users where id in
    <foreach collection="list" item="id" open="(" close=")" separator=",">
      #{id}
    </foreach>
    </select>
    

測試類

List<Integer> ids= new ArrayList<Integer>();
   ids.add(2);
   ids.add(4);
   ids.add(5);
	 List<Users> ls =	usersMapper.findByIds(ids);
	 for (Users users : ls) {
		System.out.println(users);
	}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章