这里总结了关于多参数传递时,MyBatis接收的三种方式。

(1)接口中编写方法

   public Emp getEmpByParams(Integer id,String lastNmae);

     public Emp getEmpByParam(@Param("id")Integer id,@Param("lastName")String lastNmae);

     public Emp getEmpByParam(Map<String, Object> map);

(2)编写Mapper文件

  <select id="getEmpByParams" resultType="com.eu.bean.Emp">
select id,last_name lastName,gender geder,email from Emp where id = #{param1} and last_name= #{param2}
</select>
  <select id="getEmpByParam" resultType="com.eu.bean.Emp">
select id,last_name lastName,gender geder,email from Emp where id = #{id} and last_name= #{lastName}
</select>

(3)编写测试

   public SqlSessionFactory getSqlSessionFactory() throws IOException {
String resource = "conf/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
return new SqlSessionFactoryBuilder().build(inputStream);
}
  @Test
public void testMapperPar() throws IOException {
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
//1.获取到sqlsession 不会自动提交数据
SqlSession openSession = sqlSessionFactory.openSession();
EmpDao mapper = openSession.getMapper(EmpDao.class); Emp emp = mapper.getEmpByParam(1, "张三");
System.out.println(emp); //手动提交数据
openSession.commit();
openSession.close();
} @Test
public void testMapperMap() throws IOException {
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
//1.获取到sqlsession 不会自动提交数据
SqlSession openSession = sqlSessionFactory.openSession();
EmpDao mapper = openSession.getMapper(EmpDao.class); Map<String, Object> map=new HashMap<String, Object>();
map.put("id", 1);
map.put("lastName", "张三");
Emp emp = mapper.getEmpByParam(map);
System.out.println(emp); //手动提交数据
openSession.commit();
openSession.close();
}
05-06 07:23