zoukankan      html  css  js  c++  java
  • 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);

    此时就可以这么使用:

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

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

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

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

    在mapper.xml文件中:

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

    使用的时候可以这么用:

        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;
        int size;
    }

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

    public void getEmpByIds(List<Integer> ids);

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

    #{list[0]}
  • 相关阅读:
    机器语言 汇编语言 C C++ Java C# javaScript Go 编译型语言 解释型语言
    计算机历史(二战前)
    可维护性组件的编写原则
    the lasted discuss about h5 optimize
    The last discussion about the inherit
    The last discussion about the prototype
    font-size line-height vertual-align的复杂关系
    vertical-align
    retina屏 适配问题
    XMLHttpRequest2.0的进步之处
  • 原文地址:https://www.cnblogs.com/xiximayou/p/12210273.html
Copyright © 2011-2022 走看看