(十二)Mybatis多查詢條件無法整體接受的解決方案
阿新 • • 發佈:2018-11-28
注:程式碼已託管在GitHub上,地址是:https://github.com/Damaer/Mybatis-Learning ,專案是mybatis-08-selectByMap,需要自取,需要配置maven環境以及mysql環境(sql語句在resource下的test.sql中),覺得有用可以點個小星星,小菜鳥在此Thanks~
很多時候,我們需要傳入多個引數給sql語句接收,但是如果這些引數整體不是一個物件,那麼我們應該怎麼做呢?這裡有兩種解決方案,僅供參考。
1.將多個引數封裝成為Map
測試介面,我們傳入一個Map,裡面的value是一個物件,那麼我們可以放字串,數字,以及一個student物件。
@Test
public void testselectStudentByNameAndAge(){
Student stu=new Student("lallal", 1212, 40);
Map<String,Object> map=new HashMap<String, Object>();
map.put("nameCon", "hello");
map.put("ageCon", 14);
map.put("stu", stu);
List<Student>students=dao.selectStudentByNameAndAge(map);
if (students.size()>0){
for(Student student:students)
System.out.println(student);
}
}
我們的sql介面,傳入的是一個Map,key為String,value為物件。
public List<Student>selectStudentByNameAndAge(Map<String,Object> map);
下面是sql語句,如果value是基本型別的話,我們需要使用#{},裡面一定寫對應的key,如果value是一個物件的話,裡面我們需要寫對應的key.屬性
#{stu.score}
:
<select id="selectStudentByNameAndAge" resultType="Student">
select id,name,age,score from student where name like '%' #{nameCon} '%' and age> #{ageCon} and score>#{stu.score}
</select>
2.使用索引接收多個引數
我們的測試類如下,傳入兩個引數:
@Test
public void testselectStudentByNameAndAgeV2(){
Student stu=new Student("lallal", 1212, 40);
List<Student>students=dao.selectStudentByNameAndAgeV2("hello",14);
if(students.size()>0){
for(Student student:students)
System.out.println(student);
}
}
在sql介面中使用兩個引數
public List<Student>selectStudentByNameAndAgeV2(String name,int age);
在sql語句裡面可以使用索引號,例如#{0},下標從零開始,與引數一一對應
<!-- 接受多個引數 -->
<select id="selectStudentByNameAndAgeV2" resultType="Student">
select id,name,age,score from student where name like '%' #{0} '%' and age> #{1}
</select>
個人理解:如果是簡單的多引數,比如沒有涉及到物件的,可以直接使用索引號就可以了,這樣看起來更簡單,如果涉及到引數是物件的話,需要使用物件的屬性就用不了索引號,需要使用map,如果引數較多的話,使用map更加方便,修改的時候也更有優勢。