zoukankan      html  css  js  c++  java
  • Mybatis学习笔记

    一、Mybatis简介

      MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

      mybatis文档:https://mybatis.org/mybatis-3/zh/index.html

      MyBatis 的真正强大在于它的语句映射,这是它的魔力所在。由于它的异常强大,映射器的 XML 文件就显得相对简单。如果拿它跟具有相同功能的 JDBC 代码进行对比,你会立即发现省掉了将近 95% 的代码。MyBatis 致力于减少使用成本,让用户能更专注于 SQL 代码。

      SQL 映射文件只有很少的几个顶级元素(按照应被定义的顺序列出):

    • cache – 该命名空间的缓存配置。
    • cache-ref – 引用其它命名空间的缓存配置。
    • resultMap – 描述如何从数据库结果集中加载对象,是最复杂也是最强大的元素。
    • parameterMap – 老式风格的参数映射。此元素已被废弃,并可能在将来被移除!请使用行内参数映射。
    • sql – 可被其它语句引用的可重用语句块。
    • insert – 映射插入语句。
    • update – 映射更新语句。
    • delete – 映射删除语句。
    • select – 映射查询语句。

    二、返回结果

    mybatis中resultType可选类型:

    1、java的基础类型及其包装类int,double和java.lang.Integer,java.lang.Double等

    <mapper namespace="com.xx.xx.dao.UserMapper">
        <!-- 返回值为int,resultType为int ,java.lang.Integer也可以-->
        <select id="countUser" resultType="int">
            select count(*) from user
        </select>
    </mapper>
    

    2、实体类,自己定义的实体类

    <mapper namespace="com.xx.xx.dao.UserMapper">
        <!-- 返回值为实体类,resultType为User-->
        <select id="getUser" resultType="User">
            select * from User where id=#{id}
        </select>
    </mapper>
    

    3、map类型,如果使用resultMap这里可以使用自定义map

    <mapper namespace="com.xx.xx.dao.UserMapper">
        <!-- 返回值为Map<String,Object>,resultType为map-->
        <select id="getUserSelective" resultType="map">
            select name,address,salary from User where id=#{id}
        </select>
    </mapper>
    

    Dao层的返回类型为Map<String, Object>key是对应的column值,value是数据中的数据

    4、集合,即返回的时一个List集合

    <mapper namespace="com.xx.xx.dao.UserMapper">
        <!-- 返回值为List<User>,resultType为User-->
        <select id="getUserList" resultType="User">
            select * from user
        </select>
    </mapper>
    

    Dao层的返回类型为List,返回map集合时返回的类型是List<Map<String, Object>>,只要返回的值是多条数据都是集合,集合类型就是resultType中的值

    三、传入参数

    1、顺序传递参数

    controller

    @ApiOperation(value = "多个参数查询_匿名顺序传参")
    @GetMapping("findByParams")
    public ResultMsg findByParams(Short gender,String age)
    {
        List result= employeeMapper.selectByGenderAndAge(gender,age);
        return ResultMsg.getMsg(result);
    }
    

    mapper

    List<Employee> selectByGenderAndAge(Short gender,String age );
    

    mapper映射文件

    <select id="selectByGenderAndAge" resultMap="BaseResultMap" >
      select * from employee where gender = #{gender} and age = #{age}
    </select>
    

      注意这里按参数名去引用的话会报如下错误,mybatis错误提示很细致,这里明确给我们提示,匿名参数只能使用arg1, arg0, param1, param2 类似的形式这种传参方式的缺点是不够灵活,必须严格按照参数顺序来引用

    2、 使用@Param注解

    controller

    @ApiOperation(value = "多个参数查询_注解方式传参")
    @GetMapping("findByParams2")
    public ResultMsg findByParams2(Short gender,String age)
    {
        List result= employeeMapper.selectByGenderAndAge2(gender,age);
        return ResultMsg.getMsg(result);
    }
    

    mapper

    List<Employee> selectByGenderAndAge( @Param("gender") Short gender,@Param("age") String age );
    

    mapper映射文件

    <select id="selectByGenderAndAge" resultMap="BaseResultMap" >
      select * from employee where gender = #{gender} and age = #{age}
    </select>
    

    3、使用Map传递参数

    controller

    @ApiOperation(value = "多个参数查询")
    @GetMapping("findByMapParams")
    public ResultMsg findByMapParams(Short gender,String age)
    {
        Map params = new HashMap<>();
        params.put("gender",gender);
        params.put("age",age);
        List result= employeeMapper.selectByMapParams(params);
        return ResultMsg.getMsg(result);
    }
    

    mapper

    List<Employee> selectByMapParams(Map params);
    

    mapper映射文件

    <select id="selectByMapParams" resultMap="BaseResultMap" parameterType="map">
      select * from employee where gender = #{gender} and age = #{age}
    </select>
    

    4、通过java bean传递多个参数

    controller
    controller层使用@RequestBody接收到实体类参数后,直接传递给mapper层调用即可,不需要在进行参数的转换

    @ApiOperation(value = "多个参数查询_通过Java Bean传递多个参数")
    @PostMapping("findByBeans")
    public ResultMsg findByBeans(@RequestBody Employee employee)
    {
        List result= employeeMapper.selectByBeans(employee);
        return ResultMsg.getMsg(result);
    }
    

    mapper

    List <Employee> selectByBeans(Employee employee);
    

    mapper映射文件

    <select id="selectByBeans" resultMap="BaseResultMap" parameterType="com.wg.demo.po.Employee">
      select
      *
      from employee where gender = #{gender} and age = #{age}
    </select>
    

    5、传递集合类型参数List、Set、Array

    controller

    @ApiOperation(value = "多个参数查询_通过List、Set、Array传递多个参数")
    @PostMapping("findByList")
    public ResultMsg findByList(@RequestBody List<String> list)
    {
        List result= employeeMapper.findByList (list);
        return ResultMsg.getMsg(result);
    }
    

    mapper

    List <Employee> findByList(List list);
    

    mapper映射文件

    <select id="findByList" resultMap="BaseResultMap" >
      SELECT * from employee where age in
      <foreach collection="list" open="(" separator="," close=")" item="age">
        #{age}
      </foreach>
    </select>
    

    入参数据

    ["24","33"]
    

    这里foreach表示循环操作,具体的参数含义如下:

    foreach元素的属性主要有 item,index,collection,open,separator,close。
    item表示集合中每一个元素进行迭代时的别名,
    index指定一个名字,用于表示在迭代过程中,每次迭代到的位置,
    open表示该语句以什么开始,
    separator表示在每次进行迭代之间以什么符号作为分隔符,
    
    close表示以什么结束
    
    在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况下,该属性的值是不一样的,主要有一下3种情况:
    
    1)如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
    2)如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
    3)如果传入的参数是多个的时候,我们就需要把它们封装成一个Map或者Object
    
    作者:落花桂
             
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    Shell使用
    从一道面试题谈linux下fork的运行机制
    老了,问题定位难了,xml编码解析
    javacc
    C++概述
    Notepad++中设置Windows、Unix、Mac三种行尾换行符格式间的转换
    玩转html5(一)-----盘点html5新增的那些酷酷的input类型和属性
    Java Drp项目实战—— 环境搭建
    cocos2d-x游戏开发 跑酷(八) 对象管理 碰撞检測
    电话拨号盘(带触摸振动反馈)
  • 原文地址:https://www.cnblogs.com/nthforsth/p/15294752.html
Copyright © 2011-2022 走看看