Mybatis学习笔记

Mybatis

学习环境:JDK1.8、Mysql5.7、maven3.6.1、IDEA
 

1、简介

1.1 什么是MyBatis

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

 

1.2 如何获得MyBatis

  • maven仓库:
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.4</version>
</dependency>
  • Github:https://github.com/mybatis/mybatis-3

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

1.3 持久化和持久层

数据持久化解释:保存在内存中的数据断电即失,通俗来说数据持久化就是将数据永久保存在存储设备

数据需要持久化原因:内存太贵,而且有一些对象不能丢失

持久层:包括Dao层、Service层、Controller层等,是完成持久化工作的代码块,层间界限十分明显
 

1.4 为什么需要MyBatis?

  • 帮助程序员将数据存入到数据库中
  • 搭建框架简化传统的JDBC代码
  • 优点:
    • 简单易学
    • 方便灵活
    • 解除sql与程序代码的耦合
    • 提供映射标签,支持对象与数据库的orm字段关系映射
    • 提供对象关系映射标签,支持对象关系组建维护
    • 提供xml标签,支持编写动态sql
       

2、第一个Mybatis程序

  1. 创建数据库和maven父工程
CREATE DATABASE `mybatis`

USE `mybatis`

CREATE TABLE `user`(
	`id` INT(20) NOT NULL PRIMARY KEY,
	`name` VARCHAR(30) DEFAULT NULL,
	`pwd` VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;

INSERT INTO `user`(`id`,`name`, `pwd`) VALUES
(1,'张三','123456'),
(2,'李四','123456'),
(3,'王五','123456')

​ maven父工程:新建一个空的maven项目,并删去src目录

  1. 在父工程pom.xml中导入程序运行所需依赖
<!--数据库依赖-->
<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.4</version>
</dependency>

<!--单元测试依赖-->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>
  1. 编写mybatis.xml配置文件,作用是配置数据库连接数据源以及注册mapper
<?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>
    <mappers>
        <mapper resource="com/Nana/dao/UserMapper.xml"/><!--注意这里是/做分隔符-->
    </mappers>
</configuration>
  1. 编写MybatisUtils.java工具类,目的是获取SqlSession
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    static{
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}
  1. 编写和表相对应的pojo实体类
public class User {
    private int id;
    private String name;
    private String pwd;

    public User() {
    }

    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}
  1. 编写UserDao接口
public interface UserDao {
    List<User> getUserList();
}
  1. 编写UserMapper.xml,作用类似于UserDao接口的实现类
<?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.Nana.dao.UserDao">
	<!--id作用是和getUserList建立映射,resultType表示返回对象为User类型-->
    <select id="getUserList" resultType="com.Nana.pojo.User">
    select * from mybatis.user
  </select>

</mapper>
  1. 编写测试类,成功检索出数据库表中所有数据
public class UserDaoTest {
    @Test
    public void test(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
    
        //方式一:使用getMapper获取,推荐方法
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        List<User> userList = userDao.getUserList();
    
        //方式二:不推荐
        //List<User>  userList sqlSession.selectList("com.Nana.dao.UserDao.getUserList");
    
        for(User user:userList)
            System.out.println(user);
    
        sqlSession.close();
    }
}
  1. 上述文件目录概览

在这里插入图片描述

 

注意:此处容易遇到的两个错误

错误一:在这里插入图片描述

问题:没有在mybatis文件中注册mapper

解决:在mybatis中注册mapper

<mappers>
    <mapper resource="com/Nana/dao/UserMapper.xml"/>
</mappers>

 
错误二:在这里插入图片描述

问题:没有在build中配置resources

解决:在父项目的pom.xml中添加如下配置

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
        </resource>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

 

3、CRUD

重要参数:

  • namespace:其中的包名要和Dao/mapper接口的包名一致
  • id:对应namespace 中的方法名
  • parameterType:传递的参数类型,在只有一个基本数据类型时候可以省略
  • resultType:方法返回值类型
     

3.1 带一个参数的查询(接口、Mapper、测试类):

User getUserById(int id);
<select id="getUserById" parameterType="int" resultType="com.Nana.pojo.User">
    select * from mybatis.user where id=#{id}
</select>
public void getUserById(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();

    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    User user = mapper.getUserById(1);
    System.out.println(user);

    sqlSession.close();
}

 

3.2 增加用户(接口、Mapper、测试类):

void addUser(User user);
<insert id="addUser" parameterType="com.Nana.pojo.User">
    insert into mybatis.user(id, name, pwd) values(#{id}, #{name}, #{pwd})
</insert>
public void addUser(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();

    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    mapper.addUser(new User(5,"哈哈","123456"));

    sqlSession.commit();
    sqlSession.close();
}

 

3.3 修改用户(接口、Mapper、测试类):

void updateUser(User user);
<update id="updateUser" parameterType="com.Nana.pojo.User">
    update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id}
</update>
public void updateUser(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();

    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    mapper.updateUser(new User(5, "呵呵", "111111"));

    sqlSession.commit();
    sqlSession.close();
}

 

3.4 删除用户(接口、Mapper、测试类):

void deleteUser(int id);
<delete id="deleteUser" parameterType="int">
    delete from mybatis.user where id=#{id}
</delete>
public void deleteUser(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();

    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    mapper.deleteUser(5);

    sqlSession.commit();
    sqlSession.close();
}

 

3.5 万能Map和模糊查询

如果数据库中字段很多的情况下可以考虑使用map传参,就无须传对象了

void addUser2(Map<String, Object> map);
<insert id="addUser2" parameterType="map">
    insert into mybatis.user(id, pwd) values(#{userid}, #{userpwd})
</insert>
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("userpwd", "1111111");
    mapper.addUser2(map);

    sqlSession.commit();
    sqlSession.close();
}

 
模糊查询两种书写方式

  1. java代码执行时传递通配符%%
List<User> userList = userMapper.getUserLike("%李%");
  1. 在sql拼接中使用通配符,这种方式可以防止sql注入
select * from mybatis.user where name like "%"#{value}"%"

 

4、配置解析

4.1 核心配置文件

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

注意:在增加配置时要严格按照指定顺序,否则可能会报错
 

4.2 environments(环境配置)

默认事务管理器:JDBC

默认连接池:POOLED

MyBatis可以配置成适应多种环境,但每个SqlSessionFactory实例只能选择一种环境。即可以有多个id不同的环境,default就是要使用的那个环境

在这里插入图片描述
 

4.3 properties(属性)

有三种配置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
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <properties resource="db.properties"></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>
    <mappers>
        <mapper resource="com/Nana/dao/UserMapper.xml"/>
    </mappers>
</configuration>

方法二:直接在mybatis配置文件中配置

<?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>
    <mappers>
        <mapper resource="com/Nana/dao/UserMapper.xml"/>
    </mappers>
</configuration>

方法三:可以在db.properties中配置一半,在mybatis配置文件中配置一半

driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
<?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>
    
    <properties resource="db.properties"></properties>
    
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/Nana/dao/UserMapper.xml"/>
    </mappers>
</configuration>

注意:如果外部配置文件和mybatis配置文件中有同一字段,优先使用外部配置文件的
 

4.4 typeAliases(类型别名)

类型别名即为Java类型设置一个端的名字,存在的意义仅在于用来减少类完全限定名的冗余

基本数据类型的别名是在前边加上_,如int的别名为__int

包装类的别名是将首字母变为小写,如Integer的别名为integer

有三种方法可以给实体类取别名:

方法一:在mybatis配置文件中编写typeAliases

<typeAliases>
    <typeAlias type="com.Nana.pojo.User" alias="user"></typeAlias>
</typeAliases>

方法二:可以指定一个包名,在没有使用注解的时候,会扫描这个包下的所有类,以类名首字母小写作为别名

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

方法三:在类名前使用注解,注意要导包

import org.apache.ibatis.type.Alias;

@Alias("user")

三种方法选择:第一种可以自定义别名,第二种则不行,如果非要使用第二种还要自定义别名的话要使用注解
 

4.5 settings(设置)

比较重要的设置:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rJAxAHsH-1597330009591)(Mybatis学习笔记.assets/image-20200528105748439.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lFRC2OYJ-1597330009593)(Mybatis学习笔记.assets/image-20200528105822702.png)]
 

4.6 mappers(映射器)

每一个Mapper.xml都需要在Mybatis核心配置文件中注册,有三种注册Mapper方法:

方法一:推荐方法!

<mappers>
    <mapper resource="com/Nana/dao/UserMapper.xml"/>
</mappers>

方法二:使用class文件

<mappers>
    <mapper class="com.Nana.dao.UserMapper"/>
</mappers>

方法三:使用扫描包

<mappers>
    <package name="com.Nana.dao"/>
</mappers>

方法二和方法三注意点:

  • 接口和其Mapper配置文件必须同名
  • 接口和其Mapper配置文件必须在同一个包下
     

4.7 其他配置

  • typeHandlers(类型处理器)
  • objectFactor(对象工厂)
  • plugins(插件)
    • mybatis-generator-core
    • mybatis-plus
    • 通用mapper
       

4.8 生命周期和作用域

Mybatis运行逻辑关系:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-MFQjXlmR-1597330009594)(Mybatis学习笔记.assets/image-20200528115331373.png)]

生命周期和作用域是至关重要的,因为错误的使用会导致非常严重的并发问题

SqlSessionFactoryBuilder:

  • 生命周期:一旦创建了SqlSessionFactory就不再需要
  • 作用域:局部变量

SqlSessionFactory:

  • 作用:可以简单理解为数据库连接池
  • 生命周期:一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃或者重新创建一个实例
  • 作用域:应用作用域,最简单的是使用单例模式或者静态单例模式

SqlSession:

  • 作用:可以理解为连接到连接池的一个请求

  • 生命周期:SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。用完之后需要赶紧关闭,否则会占用资源

  • 用完之后需要赶紧关闭,
     

4.9 属性名和字段名不一致问题及解决方案

问题描述:假设数据库中的密码字段字段名为pwd,而在建立实体类的时候该字段对应的属性名为password,就有可能会导致命名有值查出来却为null的情况
 

解决方案一:在查询的select语句中给原来的字段起别名,过于简单粗暴

<select id="getUserList" resultType="user">
    select id,name,pwd as password from mybatis.user where id=#{id}
</select>

解决方案二:使用ResultMap

ResultMap特点:

  • 是 MyBatis 中最重要最强大的元素
  • 设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了
  • 最优秀的地方在于,即使对它已经相当了解,但是根本就不需要显示地用到它们
<resultMap id="UserMap" type="User">
	<result column="pwd" property="password"</result>
</resultMap>

<select id="getUserById" parameterType="int" resultMap="UserMap">
    select * from mybatis.user where id=#{id}
</select>

 

5、日志

5.1 日志工厂

日志作用:在数据库操作出现异常时候,可以帮助排错

曾经使用:sout、debug

现在使用:日志工厂

在这里插入图片描述

STDOUT_LOGGING日志使用

在mybatis核心配置文件中加入以下设置:

<settings>
    <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

标准日志输出

在这里插入图片描述
 

5.2 Log4j

特点:

  • Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件,甚至是套接口服务器、NT的事件记录器、UNIX Syslog守护进程等
  • 可以控制每一条日志的输出格式
  • 通过定义每一条日志信息的级别,能够更加细致地控制日志的生成过程
  • 可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
     

使用:

  1. 导入Log4j使用所需依赖
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
  1. 编写log4j.properties配置文件
#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
log4j.rootLogger=DEBUG,console,file

#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=【%c】-%m%n

#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/Nana.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=【%p】【%d{yy-MM-dd}】【%c】%m%n

#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
  1. 在mybatis核心配置文件中加入以下设置:
<settings>
    <setting name="logImpl" value="LOG4J"/>
</settings>

标准日志输出:

在这里插入图片描述
 
简单使用:

  1. 导入所需要的包
import org.apache.log4j.Logger;
  1. 定义Logger对象,参数是当前类的class
static Logger logger = Logger.getLogger(UserDaoTest.class);
  1. 使用
logger.info("into进入了Test");
logger.debug("debug进入了Test");
logger.error("error进入了Test");

 

6、分页

作用:减少数据处理量

数据库分页语法:

SELECT * from table limit startIndex,pageSize

 
Mybatis层面实现分页:

List<User> getUserByLimit(Map<String, Integer> map);
<select id="getUserByLimit" parameterType="map" resultType="com.Nana.pojo.User">
    select * from mybatis.user limit #{startIndex},#{pageSize}
</select>
public void  getUserByLimit(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();

    Map<String,Integer> map = new HashMap<String, Integer>();
    map.put("startIndex",0);
    map.put("pageSize",2);

    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    List<User> user = mapper.getUserByLimit(map);
    for (User user1 : user) {
        System.out.println(user1);
    }

    sqlSession.close();
}

 
Java代码层面实现分页:

List<User> getUserByRowBounds();
<select id="getUserByRowBounds" parameterType="map" resultType="com.Nana.pojo.User">
    select * from mybatis.user
</select>
public void  getUserByRowBounds(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();

    RowBounds rowBounds = new RowBounds(1, 2);

    List<User> user = sqlSession.selectList("com.Nana.dao.UserMapper.getUserByRowBounds", null, rowBounds);
    for (User user1 : user) {
        System.out.println(user1);
    }

    sqlSession.close();
}

 
分页插件实现分页:

https://pagehelper.github.io/docs/howtouse/
 

7、使用注解开发

7.1 面向接口编程

使用面向接口编程根本原因:

  • 解耦 , 可拓展 , 提高复用
  • 分层开发中 , 上层不用管具体的实现 , 大家都遵守共同的标准 , 使得开发变得容易 , 规范性更好
     

面向对象和面向接口区别:面向对象的系统中,系统的各种功能是由许许多多的不同对象协作完成的。在这种情况下,各个对象内部是如何实现自己的,对系统设计人员来讲就不那么重要了。而各个对象之间的协作关系则成为系统设计的关键。小到不同类之间的通信,大到各模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是指按照这种思想来编程

关于接口的理解

  • 接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离

  • 接口的本身反映了系统设计人员对系统的抽象理解

  • 接口应有两类:

    • 第一类是对一个个体的抽象,它可对应为一个抽象体(abstract class)

      • 第二类是对一个个体某一方面的抽象,即形成一个抽象面(interface)
    • 一个体有可能有多个抽象面。抽象体与抽象面是有区别的
       

三个面向区别:

  • 面向对象是指我们考虑问题时,以对象为单位,考虑它的属性及方法
  • 面向过程是指我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现
  • 接口设计与非接口设计是针对复用技术而言的,与面向对象(过程)不是一个问题。更多的体现就是对系统整体的架构
     

7.2 使用注解

本质:反射机制实现

底层:使用动态代理

使用

  1. 在接口中实现注解
@Select("select * from user")
List<User> getUsers();
  1. 在Mybatis核心配置文件中绑定接口
<mappers>
    <mapper class="com.Nana.dao.UserMapper"/>
</mappers>
  1. 测试
public void test(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();

    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    List<User> user = mapper.getUsers();
    for (User user1 : user) {
        System.out.println(user1);
    }

    sqlSession.close();
}

 

7.3 Mybatis使用注解详细的执行流程

在这里插入图片描述
 

7.4 CRUD

tip:工具类在创建的时候传入true值可以自动提交事务

public static SqlSession getSqlSession(){
    return sqlSessionFactory.openSession(true);
}

增:

@Insert("insert into user(id,name,pwd) values (#{id},#{name},#{pwd})")
int addUser(User user);

删:

@Delete("delete from user where id=#{uid}")
int deleteUser(@Param("uid")int id);

改:

@Update("update user set name=#{name},pwd=#{pwd} where id=#{id}")
int updateUser(User user);

查:

@Select("select * from user where id=#{id}")
User getUserById(@Param("id") int id);

 
关于@Param注解:

  • 基本数据类型或者String类型需要加上,引用类型不需要加
  • 如果只有一个基本数据类型可以忽略,但是建议加上
  • 在SQL中引用的是@Param()中设定的属性名
     

8、Lombok

Lombok 是一个很方便的插件,本质是个 Java 库,使用它通过相关注解就可以不用再编写冗长的 getter 或者 equals 等方法

常用方法:

在这里插入图片描述

使用步骤:

  1. 在IDEA中安装Lombok插件

在这里插入图片描述

  1. 导入Lombok的依赖
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.12</version>
    <scope>provided</scope>
</dependency>
  1. 在实体类前边加注解
@Data
public class User {
    private int id;
    private String name;
    private String pwd;
}

 
优点:

  1. 能通过注解的形式自动生成构造器、getter/setter、equals、hashcode、toString等方法,提高了一定的开发效率
  2. 让代码变得简洁,不用过多的去关注相应的方法
  3. 属性做修改时,也简化了维护为这些属性所生成的getter/setter方法等

缺点:

  1. 不支持多种参数构造器的重载
  2. 虽然省去了手动创建getter/setter方法的麻烦,但大大降低了源代码的可读性和完整性,降低了阅读源代码的舒适度
     

9、多对一处理

9.1 前期环境搭建

  1. 建立数据库表插入数据
CREATE TABLE `teacher` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8

INSERT INTO teacher(`id`, `name`) VALUES (1, '秦老师');

CREATE TABLE `student` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
`tid` INT(10) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fktid` (`tid`),
CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8

INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('1', '小明', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('2', '小红', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('3', '小张', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('4', '小李', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('5', '小王', '1');
  1. 建立数据库实体类
@Data
public class Teacher {
    private int id;
    private String name;
}
@Data
public class Student {
    private int id;
    private String name;
    Teacher teacher;
}
  1. 建立实体类Mapper接口和相应xml文件
public interface TeacherMapper { }
public interface StudentMapper { }
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.Nana.dao.TeacherMapper"></mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.Nana.dao.StudentMapper"></mapper>
  1. 在Mybatis核心配置文件中注册Mapper
<mappers>
    <mapper class="com.Nana.dao.StudentMapper"/>
    <mapper class="com.Nana.dao.TeacherMapper"/>
</mappers>
  1. 测试环境搭建是否成功
     

9.2 按照查询嵌套处理(相当于数据库子查询)

思路:先从teacher表中查出所有数据,然后取出id这一列,再在student表中查询

<select id="getStudent" resultMap="StudentTeacher">
    select * from student
</select>

<resultMap id="StudentTeacher" type="Student">
    <result property="id" column="id"></result>
    <result property="name" column="name"></result>
    <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"></association>
</resultMap>

<select id="getTeacher" resultType="Teacher">
    select * from teacher where id = #{id}
</select>

 

9.3 按照结果嵌套处理(相当于数据库联表查询)

思路:直接给两个表的字段名取别名

<select id="getStudent2" resultMap="StudentTeacher2">
    select s.id sid,s.name sname,t.name tname
    from student s,teacher t
    where s.tid=t.id
</select>

<resultMap id="StudentTeacher2" type="Student">
    <result property="id" column="sid"></result>
    <result property="name" column="sname"></result>
    <association property="teacher" javaType="Teacher">
        <result property="name" column="tname"></result>
    </association>
</resultMap>

 

9.4 注意点

  1. property使用的是数据库中的字段名,column使用的是Bean中的属性名
  2. 注意是使用全限定名还是别名
<typeAliases>
    <package name="com.Nana.pojo"/>
</typeAliases>

 

10 一对多处理

10.1 按照查询嵌套处理

<select id="getTeacher2" resultMap="TeacherStudent2">
        select * from teacher where id=#{tid}
</select>

<resultMap id="TeacherStudent2" type="Teacher">
        <collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"></collection>
</resultMap>

<select id="getStudentByTeacherId" resultType="Student">
        select * from student where tid=#{tid}
</select>

 

10.2 按照结果嵌套处理

<select id="getTeacher" resultMap="TeacherStudent">
        select s.id sid,s.name sname,t.id tid,t.name table_name 
        from student s,teacher t 
        where s.tid=t.id AND t.id=#{tid}
</select>

<resultMap id="TeacherStudent" type="Teacher">
        <result property="id" column="tid"></result>
        <result property="name" column="tname"></result>
        <collection property="students" ofType="Student">
                <result property="id" column="sid"></result>
        </collection>
</resultMap>

 

10.3 小结

  1. 在多对一的时候使用关联association,在一对多的时候使用集合collection

  2. 要保证sql的可读性,尽量通俗易懂

  3. 如果问题不好排查可以使用日志,建议使用Log4j

  4. javaType和ofType区别

    • javaType用来指定实体类中属性的类型

    • ofType用来指定映射到List或者集合中pojo类型,是泛型中的约束类型
       

11 动态SQL

动态SQL:指根据不同条件生成不同SQL语句。本质还是SQL语句,知识可以在SQL层面,去执行一个逻辑代码。动态SQL就是在拼接SQL语句,只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了

11.1 搭建环境

  1. 在数据库中建表
CREATE TABLE `blog`(
    `id` VARCHAR(50) NOT NULL COMMENT '博客id',
    `title` VARCHAR(100) NOT NULL COMMENT '博客标题',
    `author` VARCHAR(30) NOT NULL COMMENT '博客作者',
    `create_time` DATETIME NOT NULL COMMENT '创建时间',
    `views` INT(30) NOT NULL COMMENT '浏览量'
)ENGINE=INNODB DEFAULT CHARSET=utf8
  1. 创建基础工程,构建如下目录结构

在这里插入图片描述

  1. 编写和数据库对应的实体类
@Data
public class Blog {
    private String id;
    private String title;
    private String author;
    private Date createTime;
    private int views;
}
  1. 编写mybatis核心配置文件和Mapper基础语句,核心配置文件中注意开启驼峰命名
<setting name="mapUnderscoreToCamelCase" value="true"/>

<mappers>
    <mapper class="com.Nana.dao.BlogMapper"/>
</mappers>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  1. 编写工具类,目的是获得一个没有-的uuid
@SuppressWarnings("all")
public class IDutils {
    public static String getId(){
        return UUID.randomUUID().toString().replaceAll("-","");
    }
}
  1. 编写接口和Mapper插入语句
void addBook(Blog blog);
<insert id="addBook" parameterType="Blog">
    insert into blog (id,title,author,create_time,views)
    values(#{id},#{title},#{author},#{createTime},#{views})
</insert>
  1. 向表中插入数据
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Blog blog = new Blog();
blog.setId(IDutils.getId());
blog.setTitle("Mybatis");
blog.setAuthor("狂神说");
blog.setCreateTime(new Date());
blog.setViews(9999);

mapper.addBook(blog);

blog.setId(IDutils.getId());
blog.setTitle("Java");
mapper.addBook(blog);

blog.setId(IDutils.getId());
blog.setTitle("Spring");
mapper.addBook(blog);

blog.setId(IDutils.getId());
blog.setTitle("微服务");
mapper.addBook(blog);

sqlSession.close();

 

11.2 if语句

作用:进行if判断

接口及核心mapper语句:

List<Blog> queryBlogIF(Map<String, String> map);
<select id="queryBlogIF" parameterType="map" resultType="Blog">
    select * from blog where 1=1
    <if test="title != null">
        and title=#{title}
    </if>
    <if test="author!=null">
        and author=#{author}
    </if>
</select>

 

11.3 where语句

作用:只在子元素返回任何内容的情况下才插入 “WHERE” 子句,会去除子句开头的 “AND” 或 “OR”

接口及核心mapper语句:

List<Blog> queryBlogWHERE(Map<String, String> map);
<select id="queryBlogWHERE" parameterType="map" resultType="Blog">
    select * from blog
    <where>
        <if test="title != null">
            and title=#{title}
        </if>
        <if test="author!=null">
            and author=#{author}
        </if>
    </where>
</select>

 

11.4 choose、when、otherwise语句

作用:类似于Java中的switch、case、default语句

接口及核心mapper语句:

List<Blog> queryBlogCHOOSE(Map<String, String> map);
<select id="queryBlogCHOOSE" parameterType="map" resultType="Blog">
    select * from blog
    <where>
        <choose>
            <when test="title != null">
                title = #{title}
            </when>
            <when test="author != null">
                and author = #{author}
            </when>
            <otherwise>
                and views = #{views}
            </otherwise>
        </choose>
    </where>
</select>

 

11.5 set语句

作用:动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)

接口及核心mapper语句:

void updateBlog(Map<String, String> map);
<update id="updateBlog" parameterType="map">
    update blog
    <set>
        <if test="title != null">
            title = #{title}.
        </if>
        <if test="author != null">
            author = #{author}
        </if>
    </set>
    where id = #{id}
</update>

 

11.6 sql字段

作用:将重复用到的sql字段抽象出来,便于复用

接口及核心mapper语句:

 List<Blog> queryBlogSql(Map<String, String> map);
<sql id="if-title-author">
    <if test="title != null">
        title = #{title}
    </if>
    <if test="author != null">
        and author = #{author}
    </if>
</sql>

<select id="queryBlogSql" parameterType="map" resultType="Blog">
    select * from blog
    <where>
        <include refid="if-title-author"></include>
    </where>
</select>

注意:

  • 最好基于表单来定义SQL片段
  • 为了更好的复用性不要存在where标签
     

11.7 foreach语句

作用:允许指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。也允许指定开头与结尾的字符串以及集合项迭代之间的分隔符。这个元素也不会错误地添加多余的分隔符

接口及核心mapper语句:

List<Blog> queryBlogFOREACH(Map<String, String> map);
<select id="queryBlogFOREACH" parameterType="map" resultType="blog">
    select * from blog
    <where>
        <foreach collection="ids" item="id" open="and (" close=")" separator="or">
            id = #{id}
        </foreach>
    </where>
</select>

 

12 缓存

12.1 简介

什么是缓存:

  • 存在内存中的临时数据
  • 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题

缓存作用:减少和数据库的交互次数,减少系统开销,提高系统效率。经常查询并且不经常改变的数据可以考虑使 用缓存
 

12.2 Mybatis缓存

  • MyBatis包含了一个非常强大的查询缓存特性,可以非常方便地定制和配置缓存,缓存可以极大地提升查询效率
  • MyBatis系统中默认定义了两级缓存:一级缓存二级缓存
    • 默认情况下,只有一级缓存开启(SqlSession级别的缓存,也称为本地缓存)
    • 二级缓存需要手动开启和配置,是基于namespace级别的缓存
    • 为了提高扩展性,MyBatis定义了缓存接口Cache,可以通过实现Cache接口来自定义二级缓存
       

12.3 一级缓存

  • 一级缓存也叫本地缓存:SqlSession
  • 与数据库同一次会话期间查询到的数据会放在本地缓存中
  • 以后如果需要获取相同的数据,可以直接从缓存中拿,不必再去查询数据库
  • 默认是开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段
  • 一级缓存就是一个Map
     

一级缓存测试:

  1. 开启日志
<setting name="logImpl" value="STDOUT_LOGGING"/>
  1. 编写语句测试
public User getUserById(@Param("id") int id);
<select id="getUserById" resultType="User">
    select * from user where id=#{id}
</select>
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);

User user = mapper.getUserById(1);
System.out.println(user);
System.out.println("==========================================");
User user2 = mapper.getUserById(1);
System.out.println(user2);
System.out.println(user==user2);

sqlSession.close();
  1. 测试结果,两次查询只走了一次sql语句,且查询到的是同一个地址

在这里插入图片描述
 
缓存失效情况:

  1. 查询不同内容
  2. 增删改操作,可能会改变原来的数据,所以必定会刷新缓存
  3. 查询不同的Mapper.xml
  4. 手动清理缓存
sqlSession.clearCache();

 
增删改缓存失效测试:映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存。

public void updateUser(User user);
<update id="updateUser" parameterType="User">
    update user set name=#{name},pwd=#{pwd} where id=#{id}
</update>
public void test(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);

    User user = mapper.getUserById(1);
    System.out.println(user);

    mapper.updateUser(new User(2,"aaaaa", "111111"));

    System.out.println("==========================================");
    User user2 = mapper.getUserById(1);
    System.out.println(user2);
    System.out.println(user==user2);

    sqlSession.close();
}

测试结果:更新后要重新走一次sql语句

在这里插入图片描述
 

12.4 二级缓存

  • 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
  • 是基于namespace级别的缓存,一个名称空间对应一个二级缓存
  • 工作机制
    • 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中
    • 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭后,一级缓存中的数据被保存到二级缓存中
    • 新的会话信息,可以从二级缓存中获取内容
    • 不同的mapper查出的数据会放在自己对应的缓存中
       
      二级缓存测试:
  1. 开启全局缓存
<setting name="cacheEnable" value="true"/>
  1. 在要使用二级缓存的Mapper中开启

默认缓存:

<cache/>

可修改属性缓存:

<cache
  eviction="FIFO"
  flushInterval="60000"
  size="512"
  readOnly="true"/>
  1. 编写测试语句
SqlSession sqlSession = MybatisUtils.getSqlSession();
SqlSession sqlSession2 = MybatisUtils.getSqlSession();

UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
sqlSession.close();

System.out.println("==========================================");
UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);
User user2 = mapper2.getUserById(1);
System.out.println(user2);
System.out.println(user==user2);

sqlSession2.close();
  1. 测试结果

在这里插入图片描述

注意:

  • 如果使用的是默认缓存需要将实体类序列化,否则会报错
  • 只要开启了二级缓存,在同一个Mapper下就有效
  • 所有的数据都会先放在一级缓存中,只有当会话提交或者关闭的时候,才会提交到二级缓存中

 

12.5 缓存原理

在这里插入图片描述
 

12.6 自定义缓存ehcache

使用步骤:

  1. 导入依赖
<dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-ehcache</artifactId>
    <version>1.1.0</version>
</dependency>
  1. 在Mapper中指定使用ehcache缓存
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
  1. 编写ehcache配置文件
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">

    <diskStore path="./tmpdir/Tmp_EhCache"/>

    <defaultCache
            eternal="false"
            maxElementsInMemory="10000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="259200"
            memoryStoreEvictionPolicy="LRU"/>

    <cache
            name="cloud_user"
            eternal="false"
            maxElementsInMemory="5000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="1800"
            memoryStoreEvictionPolicy="LRU"/>
</ehcache>
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值