10-动态SQL语句
生活随笔
收集整理的這篇文章主要介紹了
10-动态SQL语句
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目錄
- 一、 -if
- 二、 -where
- 三、 -foreach
- 擴展:sql語句很多重復怎么辦?
一、 -if
當你要查詢的參數不確定時:參數可能只有username或者password或者有多個甚至什么都沒有
test 類
@Testpublic void testFindByCondition(){User u=new User();u.setUsername("醉人");List<User> users=userMapping.findUserByCondition(u);for (User user:users){System.out.println(user);}}mapping.xml(大小寫、名稱一致很重要)
<!--根據條件查詢--><select id="findUserByCondition" resultType="domain.User">select *from user where 1=1/*username應該與實體表中的名字一致,包括大小寫*/<if test="username!=null">/*#{username} 應該與實體表中的名字一致,包括大小寫*/and username=#{username}</if><if test="id!=null">and id =#{id}</if></select>二、 -where
<select id="findUserByCondition" resultType="domain.User">select *from user<where><if test="username!=null">and username=#{username}</if><if test="id!=null">and id=#{id}</if></where></select>用 where 的話比只有 if 的 sql 語句更簡潔
三、 -foreach
select *from user where id in(1,2)
<select id="findUserInIds" resultType="domain.User">select *from user<where><if test="list !=null and list.size()>0"><foreach collection="list" item="item" open="and id in(" close=")" separator=",">#{item}</foreach></if></where></select> @Testpublic void testFindUserInIds(){ArrayList<Integer> list=new ArrayList<Integer>();list.add(1);list.add(2);List<User> users=userMapping.findUserInIds(list);for (User user:users){System.out.println(user);}}擴展:sql語句很多重復怎么辦?
<sql id="defaultUser">select *from user</sql>調用
注意:如果后面還要添加語句,上面的 sql 語句后面不要添加分號
<select id="findAll" resultType="domain.User"><include refid="defaultUser"/>/*select *from user;*/</select>轉載于:https://www.cnblogs.com/zuiren/p/11406127.html
總結
以上是生活随笔為你收集整理的10-动态SQL语句的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 09-事务原理和自动提交设置
- 下一篇: 11-表之间关系