一、Mapper.java 接口中的方法只有一个参数
1、mapper.xml 文件可以不使用 parameterType 这个参数,Mybatis会根据实体类(entity)的类型自动识别并匹配javaBean(这一部分在 spring配置文件关于数据源那一部分)。
public interface StudentMapper {
public int addStu(Student stu);
}
<!--<insert id="addStu" parameterType="stu">-->
<insert id="addStu">
insert into tb_stu(s_id,s_name,s_age,s_email,s_birth,s_schid)values
(#{id},#{name},#{age},#{email},#{birth},#{schid})
</insert>
2、(不推荐使用)其实仅有一个参数时,我们是没必要@Param注解的。如果用了,我们就必须用parameterType 这个参数。并且取值也有所讲究。
@Param("") 指定一个参数并取一个名字,供mapper.xml文件取值使用
public interface StudentMapper {
public int addStu(@Param("stu")Student stu);
}
<insert id="addStu" parameterType="stu">
insert into tb_stu(s_id,s_name,s_age,s_email,s_birth,s_schid)values
(#{stu.id},#{stu.name},#{stu.age},#{stu.email},#{stu.birth},#{stu.schid})
</insert>
二、Mapper.java 接口中的方法有多个参数
1、Mybatis 支持 多参数传递
- 示例:arg从0开始计数,param从1开始计数
(1)第一个参数用arg0或param1表示
(2)第二个参数用arg1或param2表示
public interface StudentMapper {
public List<Student> querySome(int start, int pageSize);
}
<select id="querySome" resultMap="map_stu">
select * from tb_stu limit #{arg0},#{arg1}
</select>
2、使用@Param
public interface StudentMapper {
public List<Student> querySome(@Param("start") int start, @Param("pageSize") int pageSize);
}
<select id="querySome" resultMap="map_stu">
select * from tb_stu limit #{start},#{pageSize}
</select>
3、把参数封装到一个参数 Map<String,Object>
StudentMapper dao = session.getMapper(StudentMapper.class);
int start = (pageNumber-1)*pageSize;
Map<String,Object> map = new HashMap<>();
map.put("start",start);
map.put("pageSize",pageSize);
List<Student> list = dao.querySome(map);
public interface StudentMapper {
public List<Student> querySome(Map<String,Object> map);
}
<select id="querySome" resultMap="map_stu">
select * from tb_stu limit #{start},#{pageSize}
</select>