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

  • 相关阅读:
    ORACLE10g R2【单实例 FS→单实例FS】
    算法理解汇总
    ORACLE10g R2【RAC+ASM→单实例FS】
    [SHOI2008]仙人掌图 II——树形dp与环形处理
    ORACLE10g R2【RAC+ASM→RAC+ASM】
    [学习笔记]动态点分治
    Java实现第九届蓝桥杯阶乘位数
    Oracle 12C R2 on Linux 7.X Data Guard 搭建文档
    [ZJOI2015]幻想乡战略游戏——动态点分治
    metabase 安装文档
  • 原文地址:https://www.cnblogs.com/yunqing/p/8084880.html
Copyright © 2011-2022 走看看