不少时候,咱们须要传入多个参数给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