Mybatis学习笔记

Mybatis学习

第一章 简介

1.1什么是mybatis

​ (1)MyBatis 是一款优秀的持久层框架。

它支持自定义 SQL、存储过程以及高级映射。

MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

​ (2)

maven仓库

<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.2</version>
</dependency>

1.2持久化

​ (1)数据持久化

​ 持久化就是将程序的数据在持久状态和瞬时状态转化的过程

​ 内存:断电即失

​ 数据库(jdbc),io文件持久化

1.3持久层

Dao层、Service层、Controller层

​ (1)完成持久化工作的代码块

​ (2)层界限十分明显

1.4为什么用Mybatis

​ (1)方便

​ (2)传统的JDBC代码太复杂了,简化框架,自动化

​ (3)帮助程序猿将数据存入数据库中

​ (4)不用Mybatis也可以,更容易上手

第二章 第一个Mybatis程序

2.1新建项目

​ (1)新建一个普通的maven项目

​ (2)删除src目录

​ (3)导入maven依赖

 <!--导入依赖-->
    <dependencies>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

    </dependencies>

2.2配置核心文件

<?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="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

</configuration>

/**编写mybatis工具类

/**
 * SqlSessionFactory 构建工厂获得sqlSession
 */
public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            //使用mybatis的第一步:获取sqlSession对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
             sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
    // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
    public static SqlSession getSqlSession(){
        SqlSession sqlSession =sqlSessionFactory.openSession();
        return sqlSession;
    }
}

2.3编写代码

​ (1)实体类

​ (2)Dao接口

public interface UserDao {
    List<User> getUserList();
}

​ (3)接口实现类

<?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=绑定一个Dao/Mapper接口-->
<mapper namespace="com.dong.dao.UserDao">
    <!--查询语句-->
    <select id="getUserList" resultType="com.dong.pojo.User">
        select * from mybatis.user;
    </select>
</mapper>

2.4测试

​ (1)编写Test类

package com.dong.dao;

import com.dong.pojo.User;
import com.dong.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class UserDaoTest {
    @Test
    public void test(){
        //获得SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //执行SQL
        UseDao userDao = sqlSession.getMapper(UseDao.class);
        userDao.getUserList();
        List<User> userList = userDao.getUserList();
         for(User user : userList){
             System.out.println(user);
         }

       //关闭SqlSession
        sqlSession.close();
    }
}

​ (2)maven都需要放

 <!--    所有的maven项目都需要加进去这个文件,在父,子pom.xml里都需要加入一下代码   -->   
<!--在build中配置resources,来防止我们资源导出失败的问题-->
    <build>
        <resources>

            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>

            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>

        </resources>
    </build>

第三章 CRUD

3.1 namespace

namespace 中的包名要和mapper接口的包名一致

3.2 select

选择、查询语句

​ (1)id:就是对应的namespace中的方法名

​ (2)resultType:Sql语句执行的返回值

​ (3)paramaterType:参数值

【注】在插入数据时遇到的错误

1、插入MySQL表时,报错:Cause: java.sql.SQLException: Incorrect string value: '\xE6\x9D\xA8","...' for column 'name' at row 1

解决:

​ (1)确保mysql版本不能太低:需要mysql 5.5+

​ 查询语句:select version()

​ (2)查询数据库编码

show variables like '%char%'

​ (3)改成utf8mb4

set character_set_server=utf8mb4

​ (4)将建好的表也转换成utf8mb4

​ ALTER TABLE TABLE_NAME CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci; (将TABLE_NAME替换成你的表名)

3.3 insert

​ (1)编写接口

public interface UserMapper {
    //查询全部用户
    List<User> getUserList();

    //根据id查询用户
    User getUserById(int id);

    //insert一个用户
    int addUser(User user);

    //修改用户
    int updateUser(User user);

    //删除一个用户
    int deleteUser(int id);
}

​ (2)实现接口

<!--对象中的属性可以直接取出来-->
    <insert id="addUser" parameterType="com.dong.pojo.User">
        insert into mybatis.user (id, name, psw) value (#{id},#{name},#{psw});
    </insert>

​ (3)编写测试

@Test
    public void addUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int res = mapper.addUser(new User(4,"哈哈","654321"));
        if(res>0){
            System.out.println("插入成功");
        }

        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }

3.4 update

​ 实现接口

<update id="updateUser" parameterType="com.dong.pojo.User">
        update mybatis.user set name=#{name},psw=#{psw} where id = #{id};
    </update>

3.5 delete

​ 实现接口

<delete id="deleteUser" parameterType="int">
        delete from mybatis.user where id = #{id};
    </delete>

【注】增删改都要添加 提交事务 的代码

3.6 万能Map

​ 假设我们的实体类,或者数据库中的表,字段或者参数过多,我们应当考虑使用Map

int addUser2(Map<String,Object> map);

<insert id="addUser2" parameterType="map">
        insert into mybatis.user (id,name,psw) values (#{userid},#{username},#{userpsw});
    </insert>

  @Test
    public void addUser2(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        Map<String,Object> map = new HashMap<String, Object>();
        map.put("userid",5);
        map.put("username","map");
        map.put("userpsw","789");
        mapper.addUser2(map);
        sqlSession.commit();

        sqlSession.close();
    }

3.7 模糊查询

   //模糊查询
    List<User> getUserLike(String value);

    <!--注意这里是:resultType=""-->
	<select id="getUserLike" resultType="com.dong.pojo.User">
        select * from mybatis.user where name like #{value}
    </select>


  @Test
    public void getUserLike(){
        //获得SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //执行SQL
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        List<User> userList = mapper.getUserLike("%a%");
        for(User user : userList){
            System.out.println(user);
        }
        sqlSession.close();
    }

第四章 配置解析

4.1 核心配置文件

​ (1)mybatis-config

properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)

4.2 配置环境(environments)

Mybatis可以配置成适应多种环境

不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。

学会使用配置多套运行环境

事务管理器(transactionManager)就是JDBC

在 MyBatis 中有两种类型的事务管理器(也就是 type="[JDBC|MANAGED]")

连接池:POOLED

4.3 属性(properties)

编写一个配置文件

db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username=root
password=123456


在核心配置文件中引入

<!--引入外部配置文件--> 
<properties resource="db.properties"/>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

【注】

​ (1)可以直接引入外部配置文件

​ (2)可以在其中增加一些属性配置

​ (3)如果两个文件由同一字段,优先使用外部配置文件的!

4.4 类型别名

​ (1) 类型别名可为 Java 类型设置一个缩写名字。

​ (2) 存在的意义仅在用于减少类完全限定名的冗余。

<!--可以给实体类起别名-->
    <typeAliases>
        <typeAlias type="com.dong.pojo.User" alias="User"/>
    </typeAliases>

​ 也可以指定一个包名,Mybatis会在包名下面搜索需要的Java Bean, 比如:

​ 扫描实体类的包,它的默认别名就为这个类的类名,首字母小写!

 <typeAliases>
        <package name="com.dong.pojo"/>
    </typeAliases>

第五章 标签

mybatis标签

1、基本标签

(1)select

<!--
id :唯一的标识符,对应接口中的方法
parameterType:传给此语句的参数的全路径名或别名
resultType :语句返回值类型或别名。注意,如果是集合,那么这里填写的是集合的泛型
-->
<select id="findUserAll" resultType="com.ahd.entity.User">
    SELECT * FROM USER
</select>

(2)insert

<!--添加,属性同上-->
<insert id="insertUser" parameterType="com.ahd.entity.User">
    INSERT INTO USER(Name,Pwd)
    VALUES(#{Name},#{Pwd})
</insert>

(3)delete

<!--同上-->
<delete id="deleteUserById" parameterType="com.ahd.entity.User">
    DELETE FROM user WHERE id=#{id}
</delete>

(4)update

同上insert

2、配置对象属性与查询结果集中列名对应关系
<!--resultMap:手动映射
        id:任意起名,但是不能重复,这个只是引用ID
        type:需要映射的实体类
        <id> :手动映射主键列
            property:实体类中的属性名
            column:数据库的列名
            javaType:属性数据类型
          | jdbcType:数据库字段的类型
        <result>:手动映射非主键列
    -->
<resultMap id="userEntityMap" type="com.ahd.user.entity.User">
    <id property="id" column="id" javaType="java.lang.Integer" ></id>
    <result property="username" column="username" javaType="java.lang.String"></result>
    <result property="password" column="password" javaType="java.lang.String"></result>
    <result property="phone" column="user_phone" javaType="java.lang.String"></result>
</resultMap>
3、动态sql

(1)if、where标签

<!--主要用来判断参数值来决定是否使用某个查询条件、判断是否更新某一个字段、判断是否插入某个字段的值-->
<!--resultMap:映射resultMap标签的ID引用-->
    <select id="selectUserById" parameterType="com.ahd.user.entity.User" resultMap="userEntityMap">
        select id,username,password,user_phone from `user`
        <where>
            <if test="id !=null and id !=''">
                and id = #{id}
            </if>
            <if test="phone !=null and phone!=''">
                and phone = #{phone}
            </if>
        </where>

        <!--select * from user where 1=1
        <if test="id !=null and id !=''">
            and id = #{id}
        </if>
        <if test="phone !=null and phone!=''">
            and phone = #{phone}
        </if>-->
 </select>

(2)trim

    <!--trim标签:主要用来处理SQL语句拼接中多余的关键字或者,
        prefix:拼接的前缀
        suffix:拼接的后缀
        suffixOverrides:去除SQL语句拼接之后的关键字and或者,
        prefixOverrides:去除SQL语句拼接之前的关键字and或者,
    -->
    <!--添加-->
    <insert id="insertUser" parameterType="com.ahd.user.entity.User">
        insert into user
        <trim prefix="( " suffix=" )" suffixOverrides=" , ">
            <if test="username !=null and username != ''">
                username,
            </if>
            <if test="password !=null and password !=''">
                password,
            </if>
            <if test="phone !=null and phone !=''">
                phone,
            </if>
        </trim>
        values
        <trim prefix="( " suffix=" )" suffixOverrides=",">
            <if test="username!=null and username !=''">#{username},</if>
            <if test="password !=null and password !=''">
                #{password},
            </if>
            <if test="phone !=null and phone !=''">
                #{phone},
            </if>
        </trim>
    </insert>

(3)foreach

 <!--/*foreach标签:遍历集合
    collection:传入的遍历集合属性名
    item:起一个属性别名
    open:开始遍历的拼接
    close:结束遍历的拼接
    separator:在拼接中使用什么符号
    */-->
    <select id="findUserByIds" parameterType="com.ahd.user.entity.UserParams" resultType="com.ahd.user.entity.User">
        select * from `user`
        <where>
            <if test="ids !=null">
                <foreach collection="ids" item="id" open="id IN (" close=")" separator=",">
                    #{id}
                </foreach>
            </if>
        </where>
    </select>

(4)set:动态指定需要改的属性数量

<set>
    <if test="username!=null and username!=''">
        username = #{username},
    </if>
    <if test="password!=null and password!=''">
        password = #{password},
    </if>
    <if test="phone!=null and phone!=''">
        user_phone = #{phone}
    </if>
</set>

(5)where

<!--*where* 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,*where* 元素也会将它们去除-->
<where>
    <if test="id!=null and id!=''">
        and id = #{id}
    </if>
    <if test="phone!=null and phone!=''">
        and user_phone = #{phone}
    </if>
</where>

第六章 多表配置

1、一对一
 <resultMap id="userEntityMap" type="com.ahd.user.entity.User">
        <id property="id" column="id" javaType="java.lang.Integer"></id>
        <result property="username" column="username" javaType="java.lang.String"></result>
        <result property="password" column="password" javaType="java.lang.String"></result>
        <result property="phone" column="phone" javaType="java.lang.String"></result>
        <!--配置一对一关系标签-->
        <!--
            association:配置一对一关系
            property:填写对方在己方的属性
            javaType:对方属性的数据类型
        -->
        <association property="baseUser" javaType="com.ahd.user.entity.BaseUser">
            <id property="id" column="id" javaType="java.lang.Integer"></id>
            <result property="dept" column="dept" javaType="java.lang.String"></result>
            <result property="market" column="market" javaType="java.lang.String" ></result>
        </association>
 </resultMap>
2、一对多
<!--配置一对多关系-->
        <!--
            collection:配置一对多关系
            property:对方在己方属性名
            ofType:指定对方的数据类型
        -->
        <collection property="userOrder" ofType="com.ahd.user.entity.UserOrder">
            <id property="orderId" column="order_id" javaType="java.lang.Integer"></id>
            <result property="userId" column="user_id" javaType="java.lang.Integer"></result>
            <result property="prise" column="prise" javaType="java.math.BigDecimal"></result>
            <result property="createTime" column="create_time" javaType="java.util.Date"></result>
        </collection>
3、案例
<!--一对一查询-->
    <select id="findUserInfoAll" resultMap="userEntityMap">
        SELECT u.*,bu.dept,bu.market FROM USER u,base_user bu
        WHERE u.id = bu.id
    </select>
<!--一对多查询-->
    <select id="findUserOrderAll" resultMap="userEntityMap">
        SELECT * FROM `user` u ,user_order uo
        WHERE u.id = uo.user_id
    </select>

第七章 mybatis缓存

1、概念
一级缓存:
    mybatis一级缓存又可以称之为sqlsession级别的缓存,也就是当我们使用参数和SQL完全一样的话,使用同一个
    sqlsession对象则会调用mapper方法,只会执行一次SQL。第二次就是直接从缓存拿。如果在调用的过程中
    执行了清除缓存的方法clearCache(),则会清除之前的缓存再次调用时又会从数据库中重新查询。
二级缓存:
    二级缓存是全局缓存,它会缓存到第三方库,使用二级缓存需要手动在核心配置文件中开启,二级缓存开启之后
    对应的xxxmapper.xml里的所有select语句都会被缓存。
    (1)实体类必须实现序列化
    (2)在核心配置文件的全局配置中开启二级缓存
    (3)在需要使用全局缓存的映射文件中使用缓存标签配置<cache>
    (4)在select标签上使用cache  userCache属性开启
2、二级缓存使用步骤

(1)实体类实现序列化

//实现Serializable接口
public class Customer implements Serializable {
    ...
}

(2)在核心配置文件(mybatis-config.x)的全局配置中开启二级缓存

    <settings>
        <!--默认值为true-->
        <setting name="cacheEnabled" value="true"/>
    </settings>

(3)使用缓存标签配置

<mapper namespace="com.ahd.customer.mapper.CustomerMapper">
    <!--
        eviction:代表缓存回收策略
            LRU:最近最少使用的,一般最长时间不用的对象
            FIFO:先进先出,按对象进入缓存的顺序来移除他们
            SOFT:软引用,它的移除机制基于垃圾回收器状态
            WEAK:弱引用,更加积极的移除基于垃圾回收器的状态
        flushInterval:缓存的刷新间隔时间,单位为毫秒。如果不配置就是当SQL被执行时才会去刷新
        readOnly:只读
        size:缓存引用数组,必须设置成一个正整数,指定缓存最多可以存储多少个对象
    -->
    <cache eviction="FIFO" flushInterval="100000" readOnly="true" size="50"></cache>
    <resultMap id="customerEntityMap" type="com.ahd.customer.entity.Customer">
        <id property="cusId" column="cus_id" javaType="java.lang.Integer"></id>
        <result property="cusName" column="cus_name" javaType="java.lang.String"></result>
        <result property="cusPhone" column="cus_phone" javaType="java.lang.String"></result>
        <result property="createTime" column="create_time" javaType="java.util.Date"></result>
        <result property="updateTime" column="update_time" javaType="java.util.Date"></result>
    </resultMap>
</mapper>

(4)在select标签上使用cache:useCache="true"

    <select id="findCustomerById" parameterType="java.lang.Integer" resultMap="customerEntityMap" useCache="true">
        SELECT * FROM customer WHERE cus_id = #{id}
    </select>
3、案例

详见mybatis0715项目。

测试类

public class CustomerTest {

    public static void main(String[] args) {
        //sqlsession级别的缓存
        //testLevel1Cache();
        //调用清除缓存的方法,sqlsession级别的缓存
        //testLevel1ClearCache();
        //二级缓存
        testLevel2Cache();
    }
    /**
     * 二级缓存测试,当第一次查询时放入缓存中,关闭当前连接对象时重新打开一个也可以从全局获取到
     * 缓存中的信息。
     * */
    private static void testLevel2Cache() {
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CustomerMapper customerMapper1 = sqlSession.getMapper(CustomerMapper.class);
        System.out.println("第一次调用");
        Customer customer1 = customerMapper1.findCustomerById(10);
        System.out.println(customer1.toString());

        //第二次调用之前  手动将第一个sqlsession对象关闭
        sqlSession.close();

        SqlSession sqlSession1 = SqlSessionUtil.openSession();
        CustomerMapper customerMapper2 = sqlSession1.getMapper(CustomerMapper.class);
        System.out.println("第二次调用");
        Customer customer2 = customerMapper2.findCustomerById(10);
        System.out.println(customer2.toString());
    }

    /** sqlsession级别的缓存当调用clearcache之后会重新从数据库中再次获取而不是从缓冲中获取*/
    private static void testLevel1ClearCache() {
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CustomerMapper customerMapper = sqlSession.getMapper(CustomerMapper.class);
        System.out.println("第一次调用SQL查询语句");
        Customer customer1 = customerMapper.findCustomerById(2);
        System.out.println(customer1.toString());
        //调用清除缓存的方法
        sqlSession.clearCache();
        System.out.println("第二次调用");
        CustomerMapper customerMapper1 = sqlSession.getMapper(CustomerMapper.class);
        Customer customer2= customerMapper1.findCustomerById(2);
        System.out.println(customer2.toString());
    }

    /** sqlsession级别的缓存*/
    private static void testLevel1Cache() {
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CustomerMapper customerMapper = sqlSession.getMapper(CustomerMapper.class);
        System.out.println("第一次调用SQL查询语句");
        Customer customer1 = customerMapper.findCustomerById(2);
        System.out.println(customer1.toString());
        System.out.println("第二次调用");
        CustomerMapper customerMapper1 = sqlSession.getMapper(CustomerMapper.class);
        Customer customer2= customerMapper1.findCustomerById(2);
        System.out.println(customer2.toString());
    }
posted @ 2020-03-23 11:24  Foreverless  阅读(222)  评论(0)    收藏  举报