在Mybatis映射文件中,对应接口方法如果只有1个参数,在mapper文件中可以使用parameterType。如果有多个参数,可以使用map或者自定义类的方式来处理。如果实在不想用这样的方法,Mybatis也支持对多个参数的定义。
Mapper接口
public interface TestMapper {
Object meth1(String para1, String para2);
/**
* p1、p2可以是任何合法的java命名方式
* xml中可以根据此标示来获取到具体传入的值
*/
Object meth2(@Param("p1")String para1, @Param("p2")String para2);
}
mapper.xml
<select id="meth1" resultType="int">
select count(*) from test
where col1 = #{0}
and clo2 = #{1}
</select>
<select id="meth2" resultType="int">
select count(*) from test
where col1 = #{p1}
and clo2 = #{p2}
</select>
上述两种方法都行的通,上述statement中不需要指定parameterType。如果不使用@Param注解方式,那么可以通过#{0}、#{1}的方式来获取参数的值,注意function中的第一个参数是0;使用了注解就按注解中定义的名字来取。推荐使用注解的方式。在方法重构时,例如增加、减少或调整参数的顺序,如果使用非注解的方式,在修改xml时就显得比较麻烦,可能里面的${0}、${1}、${2}都需要调整,而且不明确,特别是参数较多的情况下。
参数中如果有集合类型的参数,可以使用如下foreach的方式来应用参数:
<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
Mapper接口
public interface TestMapper {
Object meth1(String para1, String para2);
/**
* p1、p2可以是任何合法的java命名方式
* xml中可以根据此标示来获取到具体传入的值
*/
Object meth2(@Param("p1")String para1, @Param("p2")String para2);
}
mapper.xml
<select id="meth1" resultType="int">
select count(*) from test
where col1 = #{0}
and clo2 = #{1}
</select>
<select id="meth2" resultType="int">
select count(*) from test
where col1 = #{p1}
and clo2 = #{p2}
</select>
上述两种方法都行的通,上述statement中不需要指定parameterType。如果不使用@Param注解方式,那么可以通过#{0}、#{1}的方式来获取参数的值,注意function中的第一个参数是0;使用了注解就按注解中定义的名字来取。推荐使用注解的方式。在方法重构时,例如增加、减少或调整参数的顺序,如果使用非注解的方式,在修改xml时就显得比较麻烦,可能里面的${0}、${1}、${2}都需要调整,而且不明确,特别是参数较多的情况下。
参数中如果有集合类型的参数,可以使用如下foreach的方式来应用参数:
<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>