首页 > 技术文章 > MyBatis

linagcheng 2020-03-17 14:37 原文

mybatis

一、什么是 MyBatis ?

MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以对配置和原生Map使用简单的 XML 或注解,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。

采用 ORM 思想解决了实体和数据库映射的问题,对 jdbc进行了封装,屏蔽了 jdbc api 底层访问细节,使我 们不用与 jdbc api 打交道,就可以完成对数据库的持久化操作。

The MyBatis SQL mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor or annotations. Simplicity is the biggest advantage of the MyBatis data mapper over object relational mapping tools.
MyBatis SQL映射框架使得在面向对象的应用程序中使用关系数据型库更加容易。MyBatis使用XML描述符或注释将对象与存储过程或SQL语句耦合。简单性是MyBatis数据映射器相对于对象关系映射工具的最大优势。

二、安装与使用mybatis

1.pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.yuan</groupId>
    <artifactId>note_mybaties_01</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <dependencies>
        <!--        mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
    </dependencies>

</project>

2.实体类

xxx.java文件

package com.yuan.doman;

import java.io.Serializable;
import java.util.Date;

public class User implements Serializable{
    private Integer id;
    /**
     * 用户姓名
     */
    private String  username;
    /**
     * 用户生日
     */
    private Date    birthday;


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }


    @Override
    public String toString() {
        return  "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", birthday=" + birthday + '}';
    }
}

3.持久层接口

xxxMapper.java文件

package com.yuan.dao;

import com.yuan.doman.User;

import java.util.List;

/**
 * ,用户的持久层接口
 */
public interface UserDao {

    List<User> findAll();


}

4.映射文件

xxxMapper.xml文件

映射文件的mapper标签namespace属性的取值必须是dao接口的全限定类名

映射文件的操作配置(select),id属性的取值必须是dao接口的方法名

<?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">

<mapper namespace="com.yuan.dao.UserDao">
    <!--findAll方法-->
    <select id="findAll" resultType="com.yuan.doman.User">
        SELECT * FROM USER
    </select>
</mapper>

5.mybatis配置文件

SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--环境配置-->
        <!--默认环境-->
    <environments default="mysql">
        <!--mysql环境-->
        <environment id="mysql">
            <!--JDBC事务-->
            <transactionManager type="JDBC"></transactionManager>
            <!--POOLED连接池-->
            <dataSource type="POOLED">
            <!--四大参数-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///数据库名"/>
                <property name="username" value="数据库账户"/>
                <property name="password" value="数据库密码"/>
            </dataSource>
        </environment>
    </environments>

<mappers>
    <mapper resource="com/yuan/dao/UserDao.xml"/>
</mappers>
</configuration>

6.注意事项

第一个:创建UserDao.xml 和 UserDao.java时名称是为了和我们之前的知识保持一致。
在Mybatis中它把持久层的操作接口名称和映射文件也叫做:Mapper
所以:UserDao 和 UserMapper是一样的
第二个:在idea中创建目录的时候,它和包是不一样的
包在创建时:com.yuan.dao它是三级结构
目录在创建时:com.yuan.dao是一级目录
第三个:mybatis的映射配置文件位置必须和dao接口的包结构相同
第四个:映射文件的mapper标签namespace属性的取值必须是dao接口的全限定类名
第五个:映射文件的操作配置(select),id属性的取值必须是dao接口的方法名
第六个:当我们遵从了第三,四,五点之后,我们在开发中就无须再写dao的实现类。

三、映射文件中标签作用

1、select标签

<select
  <!-- 
    1. id(必须配置)
    id是命名空间中的唯一标识符,可被用来代表这条语句
    一个命名空间(namespace)对应一个dao接口
    这个id也应该对应dao里面的某个方法(sql相当于方法的实现),因此id应该与方法名一致
   -->
  id="selectUser"

  <!-- 
    2. parapeterType(可选配置,默认由mybatis自动选择处理)
    将要传入语句的参数的完全限定名或别名,如果不配置,mybatis会通过ParamterHandler根据参数类型默认选择合适的typeHandler进行处理
    paramterType 主要指定参数类型,可以是int, short, long, string等类型,也可以是复杂类型(如对象)
   -->
  parapeterType="int"

  <!-- 
    3. resultType(resultType 与 resultMap 二选一配置)
    用来指定返回类型,指定的类型可以是基本类型,也可以是java容器,也可以是javabean
   -->
  resultType="hashmap"
  
  <!-- 
    4. resultMap(resultType 与 resultMap 二选一配置)
    用于引用我们通过 resultMap 标签定义的映射类型,这也是mybatis组件高级复杂映射的关键
   -->
  resultMap="USER_RESULT_MAP"
  
  <!-- 
    5. flushCache(可选配置)
    将其设置为true,任何时候语句被调用,都会导致本地缓存和二级缓存被清空,默认值:false
   -->
  flushCache="false"

  <!-- 
    6. useCache(可选配置)
    将其设置为true,会导致本条语句的结果被二级缓存,默认值:对select元素为true
   -->
  useCache="true"

  <!-- 
    7. timeout(可选配置)
    这个设置是在抛出异常之前,驱动程序等待数据库返回请求结果的秒数,默认值为:unset(依赖驱动)
   -->
  timeout="10000"

  <!-- 
    8. fetchSize(可选配置)
    这是尝试影响驱动程序每次批量返回的结果行数和这个设置值相等。默认值为:unset(依赖驱动)
   -->
  fetchSize="256"

  <!-- 
    9. statementType(可选配置)
    STATEMENT, PREPARED或CALLABLE的一种,这会让MyBatis使用选择Statement, PrearedStatement或CallableStatement,默认值:PREPARED
   -->
  statementType="PREPARED"

  <!-- 
    10. resultSetType(可选配置)
    FORWARD_ONLY,SCROLL_SENSITIVE 或 SCROLL_INSENSITIVE 中的一个,默认值为:unset(依赖驱动)
   -->
  resultSetType="FORWORD_ONLY"
></select>

2、insert标签

<insert
  <!--
    同 select 标签
   -->
  id="insertProject"

  <!-- 
    同 select 标签
   -->
  paramterType="projectInfo"
  
  <!-- 
    1. useGeneratedKeys(可选配置,与 keyProperty 相配合)
    设置为true,并将 keyProperty 属性设为数据库主键对应的实体对象的属性名称
   --> 
  useGeneratedKeys="true"

  <!-- 
    2. keyProperty(可选配置,与 useGeneratedKeys 相配合)
    用于获取数据库自动生成的主键
   -->
  keyProperty="projectId"
>

3、resultMap标签

<!-- 
  1. type 对应的返回类型,可以是javabean, 也可以是其它
  2. id 必须唯一, 用于标示这个resultMap的唯一性,在使用resultMap的时候,就是通过id引用
  3. extends 继承其他resultMap标签
 -->
<resultMap type="" id="" extends="">  
  <!-- 
    1. id 唯一性,注意啦,这个id用于标示这个javabean对象的唯一性, 不一定会是数据库的主键(不要把它理解为数据库对应表的主键)
    2. property 属性对应javabean的属性名
    3. column 对应数据库表的列名
       (这样,当javabean的属性与数据库对应表的列名不一致的时候,就能通过指定这个保持正常映射了)
   -->
  <id property="" column=""/>
        
  <!-- 
    result 与id相比,对应普通属性
   -->    
  <result property="" column=""/>
        
  <!-- 
    constructor 对应javabean中的构造方法
   -->
  <constructor>
    <!-- idArg 对应构造方法中的id参数 -->
       <idArg column=""/>
       <!-- arg 对应构造方法中的普通参数 -->
       <arg column=""/>
   </constructor>
   
   <!-- 
    collection 为关联关系,是实现一对多的关键 
    1. property 为javabean中容器对应字段名
    2. ofType 指定集合中元素的对象类型
    3. select 使用另一个查询封装的结果
    4. column 为数据库中的列名,与select配合使用
    -->
  <collection property="" column="" ofType="" select="">
    <!-- 
      当使用select属性时,无需下面的配置
     -->
    <id property="" column=""/>
    <result property="" column=""/>
  </collection>
        
  <!-- 
    association 为关联关系,是实现一对一的关键
    1. property 为javabean中容器对应字段名
    2. javaType 指定关联的类型,当使用select属性时,无需指定关联的类型
    3. select 使用另一个select查询封装的结果
    4. column 为数据库中的列名,与select配合使用
   -->
  <association property="" column="" javaType="" select="">
    <!-- 
      使用select属性时,无需下面的配置
     -->
    <id property="" column=""/>
    <result property="" column=""/>
  </association>
</resultMap>

4、include标签

include标签引用,可以复用SQL片段

<sql id="sqlid">
    res_type_id,res_type
</sql>

<select id="selectbyId" resultType="com.property.vo.PubResTypeVO">
    select
    <include refid="sqlid"/>
    from pub_res_type
</select>

<!-- 等价于
select res_type_id,res_type from pub_res_type
-->

参考链接:https://www.jianshu.com/p/1d51d0fa9555

推荐阅读