不少時候,咱們須要傳入多個參數給sql語句接收,可是若是這些參數總體不是一個對象,那麼咱們應該怎麼作呢?這裏有兩種解決方案,僅供參考。java
測試接口,咱們傳入一個Map,裏面的value是一個對象,那麼咱們能夠放字符串,數字,以及一個student對象。sql
@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}
:code
<select id="selectStudentByNameAndAge" resultType="Student"> select id,name,age,score from student where name like '%' #{nameCon} '%' and age> #{ageCon} and score>#{stu.score} </select>
咱們的測試類以下,傳入兩個參數:對象
@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更加方便,修改的時候也更有優點。字符串
【做者簡介】:
秦懷,公衆號【秦懷雜貨店】做者,技術之路不在一時,山高水長,縱使緩慢,馳而不息。這個世界但願一切都很快,更快,可是我但願本身能走好每一步,寫好每一篇文章,期待和大家一塊兒交流。class