mybatis会对多参数方法进行特殊处理
例如:查询id=1,name=tom的一条数据
查询接口:
User getUserByIdAndName(Integer id,String name);
//
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- namespace:命名空间,指定为接口的全类名 selectUserById:唯一标识 resultType:返回值类型 --> <mapper namespace="com.yunqing.mybatis.dao.UserMapper">
//这种写法是错误的,mybatis会根据多个参数值封装一个map,在map的key中根据param1....paramN取值或者根据参数索引取值arg0....arg(N-1)
<!--
<select id="getUserByIdAndName" resultType="com.yunqing.mybatis.bean.User"> select * from t_user where id = #{id} and name = #{name} </select>
-->
//正确写法 1.根据参数索引
<select id="getUserByIdAndName" resultType="com.yunqing.mybatis.bean.User">
select * from t_user where id = #{arg0} and name = #{arg1}
</select>
//正确写法 2.根据参数param
<select id="getUserByIdAndName" resultType="com.yunqing.mybatis.bean.User"> select * from t_user where id = #{param1} and name = #{param2} </select>
</mapper>
建议使用的方法是
<select id="getUserByIdAndName" resultType="com.yunqing.mybatis.bean.User"> select * from t_user where id = #{id} and name = #{name} </select>
这种方法虽然是错误的,但是只要在dao层使用命名参数指定参数名,就是最正确,最明确,最建议的写法:
User getUserByIdAndName(@Param("id")Integer id, @Param("name")String name);
也可以直接传一个pojo对象,或者一个Map,或者自定义To数据传输对象
1.map参数
xml中sql
<select id="getUserByMap" resultType="com.yunqing.mybatis.bean.User"> select * from t_user where id = #{id} and name = #{name} </select>
dao
User getUserByMap(Map<String,Object> map);
test.java
@Test public void getUserByMap() throws IOException { //从xml中获取sqlSessionFactory String resource = "conf/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //获取sqlSession SqlSession sqlSession = sqlSessionFactory.openSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); Map<String,Object> map = new HashMap<>(); map.put("id",1); map.put("name","tom"); User user = userMapper.getUserByMap(map); System.out.println(user); sqlSession.close(); }