一、通过下标入参,需要注意的是第一个参数下标为0
dao方法
public List<T_user> queryT_userByPage(String page,String pageSize);
xml中:
<select id="findAgeAndSex" resultType="Animal">
select * from animal WHERE age=#{0} and sex=#{1};
</select>
二、通过dao方法中@param注解入参
dao中:
List<Animal> findAgeAndSex(@Param("age") int age,@Param("sex") String sex);
xml中:
这里参数名,要和注解中的参数名一样
<select id="findAgeAndSex" resultType="Animal">
select * from animal WHERE age=#{age} and sex=#{sex};
</select>
三、通过list集合入参
Dao中:
int addBatch(List<Animal> list);
xml中:
<insert id="addBatch">
insert into animal(aname,age,sex,feetCount)values
<foreach collection="list" item="list" separator=",">
(#{list.aname},#{list.age},#{list.sex},#{list.feetCount})
</foreach>
</insert>
测试类:
@Test
public void addBatch() {
//3 使用工厂生产SqlSession对象
SqlSession session=factory.openSession();
AnimalDynamicMapper animalMapper=session.getMapper(AnimalDynamicMapper.class);
Animal animal=new Animal(-1,"root",12,"woman",6);
Animal animal2=new Animal(-1,"king",75,"woman",9);
List<Animal> list=new ArrayList<>();
list.add(animal);
list.add(animal2);
animalMapper.addBatch(list);
session.commit();
}
四、通过map集合入参
首先将参数封装进map集合中,再传入dao方法中
Dao中:
List<Animal> findByParam(Map param);
xml中:
<select id="findByParam" resultType="Animal">
select * from animal WHERE age=#{age} and sex=#{sex};
</select>
测试类:
@Test
public void findByParam() {
//3 使用工厂生产SqlSession对象
SqlSession session=factory.openSession();
AnimalMapper animalMapper=session.getMapper(AnimalMapper.class);
Map<String,String> map=new HashMap();
map.put("age","16");
map.put("sex","man");
List<Animal> list=animalMapper.findByParam(map);
System.out.println(list);
}
五、最好用的方式
Dao
List<Animal> findAgeAndFeetcount(int age,int count);
xml:
<select id="findAgeAndFeetcount" resultType="Animal">
select * from animal WHERE age=#{param1} and sex=#{param2};
</select>
或者
<select id="findAgeAndFeetcount" resultType="Animal">
select * from animal WHERE age=#{arg0} and feetcount=#{arg1};
</select>