mybatis文件映射之当输入的参数不只一个时

前端之家收集整理的这篇文章主要介绍了mybatis文件映射之当输入的参数不只一个时前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1、单个参数:mybatis不会做处理,可以用#{参数名}来取出参数。

2、多个参数:mybatis遇见多个参数会进行特殊处理,多个参数会被封装成员一个map,#{}就是从Map中获取指定的key的值。

public void getEmpByNameAndId(Integer id,String name);

此时在mapper.xml文件中可以这么获取参数的值:

<select id="getEmpByNameAndId" resultType="com.gong.mybatis.bean.Employee"> 
select id,last_name lastName,email,gender from tbl_employee where id = #{param1} and last_name=#{param2}
</select>

param1...n按顺序来写。

当然我们也可以在接口中的方法提前先指定参数的名称

public Employee getEmpByNameAndId(@Param("id") Integer id,@Param("lastName") String name);

此时就可以这么使用:

>

3、当输入的参数正好是业务逻辑的数据模型,我们就可以直接传入pojo,通过#{属性名}取出pojo的属性值。

4、如果多个参数不是业务逻辑的数据,如果没有对应的pojo,为了方便,我们可以传入map:

void getEmpByMap(Map<String,Object> map);

在mapper.xml文件中:

    ="getEmpByMap">
        select id,gender from tbl_employee where id = #{id} and last_name=#{lastName}
    >

使用的时候可以这么用:

    public sqlSessionFactory getsqlSessionFactory() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream is = Resources.getResourceAsStream(resource);
        return new sqlSessionFactoryBuilder().build(is);
    }
    sqlSessionFactory sqlSessionFactory = getsqlSessionFactory();
    //不会自动提交数据
    sqlSession openSession = sqlSessionFactory.openSession();
    EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
    Map<String,Object> map = new HashMap<>();
    map.put("id",1);
    map.put("lastName","xiximayou");
    Employee employee = mapper.getEmpByMap(map);

5、如果多个参数不是数据模型但是需要经常使用到,那么可以自定义TO(Transfer Object)数据传输对象,比如在分页时一般会有:

Page{
    int index;
     size;
}

6、如果是Collection(List、Set)类型或者是数组,也会特殊处理,把传入的list或者数组封装在map中:

void getEmpByIds(List<Integer> ids);

如果传入的是List,可以这么获取值:

#{list[0]}

猜你在找的Mybatis相关文章