動態sql:sql
映射文件代碼:數組
1 <!-- 動態sql,根據名字和年齡查詢,where標籤會處理第一個and,其餘位置的and不會自動處理 --> 2 <select id="queryStudentByNameAndAge" parameterType="student" resultMap="student1"> 3 select * from student 4 <!-- 1.使用where 1=1 ,避免where後直接跟and --> 5 <!-- 2.使用where關鍵字,避免where後直接跟and --> 6 <where> 7 <if test="sname != null and sname != '' "> 8 and sname = #{sname} 9 </if> 10 <if test="age != null and age != '' "> 11 and age = #{age} 12 </if> 13 </where> 14 </select>
foreach循環屬性集合:app
映射文件:測試
<!-- foreach循環屬性集合--> <select id="queryStudentsByHomeAddress" parameterType="Home" resultMap="student1"> select * from student <where> <if test="homeAddress != null and homeAddress != '' "> <!-- colleaction是屬性中的集合,item是遍歷出來的每一個元素,open是循環結果前邊的東西,close是循環結果後邊要加的東西,separator是循環結果用什麼符號分隔 --> <foreach collection="homeAddress" item="homeAr" open=" and homeaddress in (" close=" )" separator=","> #{homeAr} </foreach> </if> </where> </select>
測試類:spa
1 Home home = new Home(); 2 List<String> homeAddress = new ArrayList<String>(); 3 homeAddress.add("北京"); 4 homeAddress.add("南京"); 5 home.setHomeAddress(homeAddress); 6 List<Student> stu = studentMapper.queryStudentsByHomeAddress(home);
foreach循環集合:code
映射文件:(須要注意的是循環要循環list)對象
1 <!-- foreach循環集合--> 2 <select id="queryStudentsWithList" parameterType="list" resultMap="student1"> 3 select * from student 4 <where> 5 <!-- 必須寫list --> 6 <if test="list != null and list != '' "> 7 <foreach collection="list" item="homeAr" open=" and homeaddress in (" close=" )" separator=","> 8 #{homeAr} 9 </foreach> 10 </if> 11 </where> 12 </select>
測試類:blog
1 List<String> list = new ArrayList<String>(); 2 list.add("北京"); 3 list.add("南京"); 4 List<Student> stu = studentMapper.queryStudentsWithList(list);
foreach循環數組:it
映射文件:(注意循環必須都寫array,輸入參數不是簡單類型時都寫Object[])io
1 <!-- foreach循環數組--> 2 <select id="queryStudentsWithArray" parameterType="Object[]" resultMap="student1"> 3 select * from student 4 <where> 5 <!-- 必須寫array --> 6 <if test="array != null and array != '' "> 7 <foreach collection="array" item="homeAr" open=" and homeaddress in (" close=" )" separator=","> 8 #{homeAr} 9 </foreach> 10 </if> 11 </where> 12 </select>
測試類:
1 String[] str = {"北京","南京"}; 2 List<Student> stu = studentMapper.queryStudentsWithArray(str);
foreach循環對象數組:
映射文件:(須要注意的是這時的item要寫循環出來的對象了,不能瞎寫名字了,而後經過對象點的方式獲取值)
1 <!-- foreach循環對象數組--> 2 <select id="queryStudentsWithObjectArray" parameterType="Object[]" resultMap="student1"> 3 select * from student 4 <where> 5 <!-- 必須寫array --> 6 <if test="array != null and array != '' "> 7 <!-- item裏邊寫的是循環出來的對象 --> 8 <foreach collection="array" item="address" open=" and homeaddress in (" close=" )" separator=","> 9 <!-- 對象點屬性獲取值 --> 10 #{address.homeAddress} 11 </foreach> 12 </if> 13 </where> 14 </select>
測試類:
1 Address addr1 = new Address(); 2 addr1.setHomeAddress("北京"); 3 Address addr2 = new Address(); 4 addr2.setHomeAddress("南京"); 5 Address[] address = {addr1,addr2}; 6 List<Student> s = studentMapper.queryStudentsWithObjectArray(address);