zoukankan      html  css  js  c++  java
  • 8、mybatis学习——sqlmapper配置文件参数处理(单个参数,多个参数,命名参数)

    1、单个参数时

      

     此时sqlMapper中的配置

      

     或者

      

     都可以;因为参数只有一个,不会混乱,只有单个参数时红框中的取名可随意

    2、多个参数时

        mapper接口中的方法:

      

         sqlmapper中的配置:

        <!-- 多个参数时,mybatis会做特殊处理;多个参数会被封装成一个map
          key:param1,param2,.......paramN
          value:传入的参数值
          #{ }就是从map中获取指定key的值 -->
        <select id="selectEmpByIdAndName" resultType="employee">
            select * from employee where id = #{param1} and name = #{param2}
        </select>

    3、多个参数时(命名参数方式)

        mapper接口中的方法:利用@Param配置进行命名参数

         sqlmapper中的配置:

        <!-- 多个参数命名方式 -->
        <select id="selectEmpByIdAndName" resultType="employee">
            select * from employee where id = #{id} and name = #{name}
        </select>

    4、参数为POJO类

      mapper接口中的方法:

       sqlmapper中的配置:

      #{属性名}:取出传入的pojo的对应属性值

        <insert id="addEmp" parameterType="employee" >
            insert into employee(name,gender) values(#{name},#{gender})
        </insert>

    5、如果多个参数不是业务模型中的数据,没有对应的pojo,(这些参数不经常使用的前提下为了方便,也可以直接传入map(不用@Param注解时,mybatis默认把多个参数封装在一个map中),自己封装可以指定key值;可以和上面第二点对比

      mapper接口中的方法:

      sqlmapper中的配置

        <select id="selectEmpByIdAndName" resultType="employee">
            select * from employee where id = #{idtest} and name = #{nametest}
        </select>

      测试方法中传入map

        @Test
        public void test3() throws IOException {
            String source = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(source);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            
            //获取sqlSession实例,能直接执行映射的sql语句
            SqlSession sqlSession = sqlSessionFactory.openSession();
            EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
            Map map = new HashMap();
            map.put("idtest", 1);
            map.put("nametest", "xiaohon");
            Employee employee = employeeMapper.selectEmpByIdAndName(map);
            System.out.println(employee);
            sqlSession.close();
        }

    6、如果多个参数不是业务模型中的数据,没有对应的pojo,(另外这些参数经常使用),可以编写一个TO(Transfer Object)数据传输对象进行封装对象,进行传参

  • 相关阅读:
    dnsServer SmartDNS / smartdns / DNS UDP 53
    springBoot 自定义注解 + 自定义异常捕获实战
    查询出ES库所有数据
    springBoot2.X 支持http、https访问
    配置ES IK分词器自定义字典
    搭建angular开发环境 运行 ng-alain框架
    【jQuery】 选择器
    【jQuery】 js 对象
    【C#】 URL Protocol
    【C#】 反射
  • 原文地址:https://www.cnblogs.com/lyh233/p/12342472.html
Copyright © 2011-2022 走看看