JavaEE-Mybatis知识点笔记

本文详细介绍了 MyBatis 框架,包括其功能、优势以及如何配置和使用。从搭建环境、创建数据库表到编写实体类、Mapper 接口和 XML 映射文件,一步步展示了 CRUD 操作。还讨论了日志、分页、动态 SQL 和缓存等高级特性,以及如何处理一对多和多对一的关系。最后提到了 Lombok 库的使用,以简化实体类的代码。
摘要由CSDN通过智能技术生成

1,简介

1.1,什么是mybatis?

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

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

如何获得mybatis?

maven仓库:

github:

1.2,持久化

数据持久化:

  • 将程序的数据在持久状态和瞬时状态转化的过程
  • 内存:断电即失
  • 数据库(jdbc),io文件持久化。
  • 生活:冷藏,罐头。

为什么需要持久化?

  • 有一些对象不能让他丢掉。
  • 内存太贵了

1.3,持久层

dao层,service层,controller层

  • 完成持久化工作的代码块
  • 层界限十分明显

1.4,为什么需要mybatis?

  • 方便
  • 传统的jdbc代码太复杂,简化。框架
  • 帮助程序员将数据存入数据库中
  • 不用mybatis也可以,更容易上手。技术没有高低之分
  • 优点:

2,第一个mybatis程序

思路:搭建环境->导入mybatis->编写代码->测试

2.1,搭建环境

创建数据库

image-20210311143728290

1,新建一个普通的maven项目,

2,删除src目录(把本项目当做父工程)

3,导入maven依赖


<!--    导入依赖-->
<dependencies>
<!--    mysql驱动-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.21</version>
    </dependency>

    <!--    mybaits-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.6</version>
    </dependency>

    <!--junit-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>
</dependencies>

2.2,创建一个模块

  • 编写mybatis的核心配置文件

<!--核心配置文件-->
<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?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

<mappers>
    <mapper resource="dao/UserMapper.xml"/>
</mappers>
</configuration>
  • 编写mybatis工具类
package utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory = null;

    static {
        String config = "mybatis-config.xml";  //需要和你项目中的文件名一样

        try {
            InputStream in = Resources.getResourceAsStream(config);
            //创建SQLSessionFactory对象,使用SqlSessionFactoryBuild对象
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //获取SQLSession的方法
    public static SqlSession getSqlSession(){
        SqlSession sqlSession = null;
        if(sqlSessionFactory != null){
            sqlSession = sqlSessionFactory.openSession(true);  //自动提交事务
        }
        return sqlSession;

    }

}

2.3,编写代码

实体类

package 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 + '\'' +
                '}';
    }
}

dao接口

package dao;

import pojo.User;

import java.util.List;

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

接口实现类(由原来的UserDaoImpl转变为一个Mapper配置文件)


<!--namespace=绑定一个dao接口(mapper接口)-->
<mapper namespace="org.mybatis.example.BlogMapper">
    <select id="getUserList" resultType="pojo.User">
        select * from mybatis.user
    </select>
</mapper>

2.4,测试junit

注意点:

image-20210311163312807

 <!--    在buil中配置resource,来防止我们资源导出失败的问题-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources
                </directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java
                </directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>

    </build>

可能出现的问题:

1,配置文件没有注册

image-20210311163605029

2,绑定接口错误(namespace)

image-20210311163632099

3,方法名不对

4,返回类型不对

5,maven导出资源问题

报如下错误:

org.apache.ibatis.exceptions.PersistenceException: 
### Error building SqlSession.
### The error may exist in dao/UserMapper.xml
### Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource dao/UserMapper.xml
	

image-20210311164045141

测试代码:

package dao;

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

import java.util.List;

public class UserDaoTest {
    @Test
    public void test(){
//        1,获得sqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
//        执行sql
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        List<User> userList = mapper.getUserList();

            System.out.println(userList);

//        关闭sqlSession
        sqlSession.close();

    }
}

结果:image-20210311163826012

3,CRUD

3.1,namespace

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

3.2,select,insert,update,delete

id:就是对应的namespace的方法名

resultType:sql语句执行的返回值

parameterType:参数类型!

1,编写接口

package dao;

import pojo.User;

import java.util.List;

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,编写对应mapper的sql语句

<?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="dao.UserMapper">
    <select id="getUserList" resultType="pojo.User" >
        select * from mybatis.user
    </select>
    <select id="getUserById" parameterType="int" resultType="pojo.User">
        select  * from  mybatis.user where id =#{id}
    </select>

    <insert id="addUser" parameterType="pojo.User">
    insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd});
    </insert>
    <update id="updateUser" parameterType="pojo.User">
        update mybatis.user  set name=#{name},pwd=#{pwd} where id=#{id};
    </update>
    <delete id="deleteUser" parameterType="int">
        delete  from mybatis.user  where id=#{id}
    </delete>


</mapper>

3,测试

package dao;

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

import java.util.List;

public class UserDaoTest {
    @Test
    public void test(){
//        1,获得sqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
//        执行sql
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.getUserList();

            System.out.println(userList);

//        关闭sqlSession
        sqlSession.close();

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

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

        sqlSession.close();

    }
    //增删改需要事务
    @Test
    public  void  addUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int aa = mapper.addUser(new User(5, "rose", "123456"));
        if (aa>0){
            System.out.println("插入成功!!");
        }
        //提交事务
        sqlSession.commit();
        sqlSession.close();

    }
    //增删改需要事务
    @Test
    public  void  updateUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int aa = mapper.updateUser(new User(5, "jack", "654321"));
        if (aa>0){
            System.out.println("修改成功!!");
        }
        //提交事务
        sqlSession.commit();
        sqlSession.close();

    }
    //增删改需要事务
    @Test
    public  void  deleteUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

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

        System.out.println("delete成功!!");

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

    }

}

注意点:增删改需要事务!!

3.3,万能的map

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

//万能的map
   int addUser2(Map<String ,Object> map);

  <insert id="addUser2" parameterType="map">
        insert into mybatis.user (id,name,pwd) values (#{userid},#{username},#{pass});
    </insert>
  //增删改需要事务
    @Test
    public  void  addUser2(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

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

        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("userid",6);
        map.put("username","hony");
        map.put("pass","123456");
      mapper.addUser2(map);

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

    }

结果:

image-20210313213431761

image-20210313214507696

3.4,模糊查询

1,java代码执行的时候,传递通配符% %

List<User> list = mapper.getUserLike("%陈%");

2,在sql拼接中使用通配符!

select  * from user where  name like "%"#{value }"%"

4,配置解析

4.1,核心配置文件

  • mybatis-config.xml
  • mybatis的配置文件包含了会深深影响mybatis行为的设置和属性信息
  • image-20210314185718461

4.2,环境变量

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

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

会使用配置多套运行环境。(看文档)

mybatis默认的事务管理器就是jdbc,连接池:POOLED

4.3,属性(properties)优化

我们可以通过属性来实现引用配置文件

这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。【db.properties】

image-20210314192243010

编写配置文件

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
username=root
password=123456

在核心配置文件中引入

image-20210314193044113

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

    <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="dao/UserMapper.xml"/>
</mappers>
</configuration>

运行结果和之前一样

image-20210314193214486

4.4,类型别名(typeAliases)优化

  • 类型别名可为 Java 类型设置一个缩写名字
  • 它仅用于 XML 配置,意在降低冗余的全限定类名书写
<!--    可以给实体类取别名-->
    <typeAliases>
        <typeAlias type="pojo.User" alias="User"/>
    </typeAliases>

也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean

比如:

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

<!--    可以给实体类取别名-->
    <typeAliases>
        <package name="pojo"/>

    </typeAliases>

在实体类比较少时,使用第一种方式。

如果实体类十分多,建议使用第二种。

第一种可以DIY别名,第二种不行,如果非要改,需要在实体类上增加注解

@Alias("user")
public class User {
    
}

4.5,设置(settings)

image-20210314205108986

image-20210314205040154

4.6,其他配置

image-20210315205527907

4.7,映射器(mappers)

image-20210315205745799

方式一:

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

方式二:使用class文件绑定注册

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

注意点:

  • 接口和Mapper配置文件必须同名

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

    image-20210315210346669

方式三:使用包扫描进行注入绑定

<mappers>
    <package name="dao"/>
</mappers>

注意点和方式二一样

4.8,生命周期和作用域

image-20210315211251967

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

SqlSessionFactoryBulider

  • 一旦创建了 SqlSessionFactory,就不再需要它了。
  • 局部变量

SqlSessionFactory

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

SqlSession

  • 连接到连接池的一个请求
  • SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域
  • 用完之后需要赶紧关闭,否则资源被占用

image-20210315211949946

这里面 的每一个mapper,就代表一个具体的业务!

5,解决属性名和字段名不一致的问题

5.1,问题

数据库中的字段:

image-20210315212130338

新建一个项目,拷贝之前的,测试实体类字段不一致的情况

public class User {
    private  int id;
    private String name;
    private  String password;
}

结果:

image-20210315212902410

解决办法:

  • 取别名(简单粗暴)
 <select id="getUserById" parameterType="int" resultType="pojo.User">
        select  id,name,pwd as password from user where id =#{id}
    </select>

image-20210315213320818

5.2,resultMap

resultMap:结果集映射

id	name	pwd
id	name	password
  <select id="getUserById"  resultMap="UserMap">
        select *from user where id =#{id}
    </select>
<!--    结果集映射-->
    <resultMap id="UserMap" type="User">
<!--        column:数据库中的字段,property:实体类中的属性-->
        <result column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="pwd" property="password"/>
    </resultMap>

  • resultMap 元素是 MyBatis 中最重要最强大的元素
  • ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了
  • ResultMap 的优秀之处——你完全可以不用显式地配置它们

6,日志

6.1,日志工厂

如果一个数据库操作出现了异常,我们需要拍错,日志就是很好的工具。

image-20210321200040783

  • SLF4J
  • LOG4J 【掌握】
  • LOG4J2
  • JDK_LOGGING
  • COMMONS_LOGGING
  • STDOUT_LOGGING 【掌握】
  • NO_LOGGING

mybatis中具体使用哪一个日志实现,在设置中设定。

STDOUT_LOGGING 标准日志输出

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

image-20210321200828860

6.2,LOG4J日志输出

什么是log4j?

  • Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件
  • 我们也可以控制每一条日志的输出格式
  • 通过定义每一条日志信息的级别
  • 通过一个配置文件来灵活地进行配置,而不需要修改应用的代码

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

报错:Cause: java.lang.NoClassDefFoundError: org/apache/log4j/Priority

image-20210321201227618

原因:没有导包!!

步骤:

1,先导包

  <dependencies>
 		<dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>

2,log4j.properties

#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码log4j.rootLogger=DEBUG,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/cdd.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

3,配置log4j为日志的实现

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

4,log4j的使用

image-20210321205717034

简单使用

1,导包

import org.apache.log4j.Logger;

2,日志对象,参数为当前类的class

     static Logger logger = Logger.getLogger(UserDaoTest.class);

3,日志级别

public  void testLog4j(){
        logger.info("info:进入了testLog4j");
        logger.debug("debug:进入了testLog4j");
        logger.error("error:进入了testLog4j");

    }

7,分页

减少数据的处理量

7.1,使用limit分页

select * from user limit startIndex,pageSize;
select * from user limit 0,2;

mybatis实现分页,核心sql:

1,接口

   //分页查询全部用户
   List<User> getUserByLimit(Map<String,Integer> map);

2,Mapper.xml

   <resultMap id="UserMap" type="User">
<!--        column:数据库中的字段,property:实体类中的属性-->
<!--        <result column="id" property="id"/>-->
<!--        <result column="name" property="name"/>-->
        <result column="pwd" property="password"/>
    </resultMap>

<!--    分页-->
<select id="getUserByLimit" parameterType="map" resultMap="UserMap">
    select  * from  user  limit #{startIndex},#{pageSize}
</select>

3, 测试

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

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        
        HashMap<String, Integer> map = new HashMap<>();
        map.put("startIndex",0);
        map.put("pageSize",3);
        List<User> userByLimit = mapper.getUserByLimit(map);

      
            System.out.println(userByLimit);
            
       
        sqlSession.close();
    }

image-20210321220926507

7.2,RowBounds分页

不再使用sql实现分页

1,接口

List<User> getUserByRowBounds();

2,mapper.xml

 <select id="getUserByRowBounds" resultMap="UserMap">
        select  * from  user
    </select>

3,测试


    @Test
    public void getUserByRowBounds(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //RowBounds分页
        RowBounds rowBounds = new RowBounds(1, 2);
        List<User> userList = sqlSession.selectList("dao.UserMapper.getUserByRowBounds",null,rowBounds);

        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }

7.3,分页插件PageHelper

网址:https://pagehelper.github.io/

image-20210324084900302

8,使用注解开发

8.1,面向接口编程

image-20210324085406793

image-20210324085441676

8.2,使用注解

1,注解在接口上实现

@Select("select * from user")
   List<User> getUsers();

2,需要在核心配置文件(mybatis-config.xml)中绑定接口

<!--绑定接口-->
    <mappers>
        <mapper class="dao.UserMapper"/>

    </mappers>

3,测试

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

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

        List<User> users = mapper.getUsers();
        for (User user : users) {
            System.out.println(user);
        }
        sqlSession.close();

    }

image-20210324091457643

本质:反射机制

底层:动态代理

8.3,CRUD

1,工具类创建的时候自动提交事务

package utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory = null;

    static {
        String config = "mybatis-config.xml";  //需要和你项目中的文件名一样

        try {
            InputStream in = Resources.getResourceAsStream(config);
            //创建SQLSessionFactory对象,使用SqlSessionFactoryBuild对象
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //获取SQLSession的方法
    public static SqlSession getSqlSession(){
        SqlSession sqlSession = null;
        if(sqlSessionFactory != null){
            sqlSession = sqlSessionFactory.openSession(true);  //自动提交事务
        }
        return sqlSession;

    }

}

2,编写接口,增加注解

package dao;

import org.apache.ibatis.annotations.*;
import pojo.User;

import java.util.List;
import java.util.Map;

public interface UserMapper {

   @Select("select * from user")
   List<User> getUsers();

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

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

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

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

}

3,测试类

import dao.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import pojo.User;
import utils.MybatisUtils;

import java.util.List;

public class UserMapperTest {

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

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//查询全部
//        List<User> users = mapper.getUsers();
//        for (User user : users) {
//            System.out.println(user);
//        }
//
//按id查询
//        User userById = mapper.getUserById(1);
//        System.out.println(userById);
//插入
//         mapper.addUser(new User(8, "小李", "987654"));
//修改
     //   mapper.updateUser(new User(8,"小光","123456"));
//删除
        mapper.deleteUser(7);

        sqlSession.close();
    }
}

[注意:]一定要将接口绑定在核心配置文件(mybatis-config.xml)中!!

<!--绑定接口-->
    <mappers>
        <mapper class="dao.UserMapper"/>
    </mappers>

关于@Param() 注解

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

#{} ${} 区别

image-20210324095145518

9,Lombok

Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java.
Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more.

  • java library
  • plugs
  • build tools
  • with one annotation your class

使用步骤:

1,在idea中安装Lombok插件

file->settings->plugins搜索Lombok并安装

2,在项目包中导入lombk的jar包

maven搜索

 <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.16</version>
            <scope>provided</scope>
        </dependency>

3,在实体类上加注解

package pojo;

import lombok.Data;
import org.apache.ibatis.type.Alias;

@Data
public class User {
    private  int id;
    private String name;
    private  String password;


}

image-20210324101035763

@Getter and @Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
@Data
@Builder
@SuperBuilder
@Singular
@Delegate
@Value
@Accessors
@Wither
@With
@SneakyThrows

说明:

@AllArgsConstructor//有参构造
@NoArgsConstructor//无参构造
@Data//无参构造,get,set,tostring,hashcode,equals

image-20210324101308203

10,多对一的处理

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,导入lombok

2,新建实体类Teacher,Student

3,建立Mapper接口

4,建立Mapper.xml配置文件

5,在核心配置文件中绑定注册Mapper接口或者文件

6,测试查询是否成功

按照查询嵌套处理

<?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="dao.StudentMapper">

<!--    思路:-->
<!--    1,查询所有的学生-->
<!--    2,根据查询出来的学生tid,寻找对应的老师-->
<!--    -->
    <select id="getStudent" resultMap="StudentTeacher">
    select * from student
    </select>

    <resultMap id="StudentTeacher" type="Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
<!--       复杂的属性需要单独处理
            对象:association
            集合:collection

-->
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
    </resultMap>

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

</mapper>

按照结果嵌套处理

<!--    按照结果嵌套处理-->

    <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 property="name" column="sname"/>
        <association property="teacher" javaType="Teacher">
            <result property="name" column="tname"/>
        </association>
    </resultMap>

11,一对多的处理

1,搭建环境

实体类:

@Data
public class Student {
    private int id;
    private String name;
    private int tid;
}

@Data
public class Teacher {
    private  int id;
    private String name;
    private List<Student> students;
}

按照结果嵌套处理

<mapper namespace="dao.TeacherMapper">
    <select id="getTeacher" resultMap="TeacherStudent">
        select s.id sid,s.name sname,t.name tname,t.id tid
        from teacher t,student s
        where s.tid=t.id and t.id=#{tid}
    </select>
    <resultMap id="TeacherStudent" type="Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
        <!--       复杂的属性需要单独处理
            对象:association
            集合:collection
            javaType:指定属性的类型
            集合中的泛型信息,我们用ofType获取
            -->
        <collection property="students" ofType="Student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="tid" column="tid"/>
        </collection>
    </resultMap>
</mapper>

image-20210326105324802

按照查询嵌套处理

image-20210326105123164

image-20210326105732108

image-20210326105758932

12,动态SQL

根据不懂的条件生成不同的sql语句

如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。

  • if
  • choose (when, otherwise)
  • trim (where, set)
  • foreach

搭建环境

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,导包

2,编写配置文件

3,编写实体类

@Data
public class blog {

    private String id;
    private  String title;
    private  String author;
    private Date createTime;//核心配置文件配置属性不一致问题
    private int views;
}

image-20210326113522816

  <settings>
        <setting name="logImpl" value="LOG4J"/>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

4,编写实体类对应Mapper接口和Mapper.xml文件

//插入数据
    int addBlog(Blog blog);
<mapper namespace="dao.BlogMapper">
    <insert id="addBlog" parameterType="blog">
        insert into mybatis.blog(id, title, author, create_time, views)
        VALUES(#{id},#{title},#{author},#{createTime},#{views})
    </insert>
</mapper>

插入数据

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

        Blog blog = new Blog();
        blog.setId(IDUtils.getId());
        blog.setTitle("Mybatis");
        blog.setAuthor("CDD");
        blog.setCreateTime(new Date());
        blog.setViews(9999);

        mapper.addBlog(blog);


        blog.setId(IDUtils.getId());
        blog.setTitle("Java");
        mapper.addBlog(blog);

        blog.setId(IDUtils.getId());
        blog.setTitle("SSM");
        mapper.addBlog(blog);

        blog.setId(IDUtils.getId());
        blog.setTitle("微服务");
        mapper.addBlog(blog);

        blog.setId(IDUtils.getId());
        blog.setTitle("云计算");
        mapper.addBlog(blog);

        sqlSession.close();
    }

image-20210326124914223

if

需求:可以指定某一项,某几项查询,不指定时查询全部

    //查询博客
    List<Blog> queryBlogIf(Map map);
<select id="queryBlogIf" parameterType="map" resultType="Blog">
    select * from mybatis.blog where  1=1
    <if test="title !=null">
        and title=#{title}
    </if>
    <if test="author!=null">
        and author= #{author}
    </if>
    </select>
 @Test
    public void queryBlogIfTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap hashMap = new HashMap();

        //hashMap.put("title","SSM");
        hashMap.put("author","CDD");

        List<Blog> blogs = mapper.queryBlogIf(hashMap);


        for (Blog blog : blogs) {
            System.out.println(blog);
        }
        
        sqlSession.close();
    }
}

image-20210328193248420

choose (when, otherwise)

<select id="queryBlogChoose" parameterType="map" resultType="blog">
        select * from mybatis.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>

trim (where, set)

    <select id="queryBlogIf" parameterType="map" resultType="Blog">
    select * from mybatis.blog
<where>
    <if test="title !=null">
        title=#{title}
    </if>
    <if test="author!=null">
     and  author= #{author}
    </if>
</where>
    </select>
<update id="updateBlog" parameterType="map">
        update mybatis.blog
        <set>
            <if test="title!=null">
                title=#{title},
            </if>
            <if test="author!=null">
                author=#{author}
            </if>
        </set>
        where id=#{id}
    </update>

image-20210328215520181

image-20210328215540103

所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码

SQL片段

有的时候,我们可能会将一些公共部分从抽取出来,以便复用

1,使用SQL标签抽取公共的部分

2,在需要使用的地方使用include标签引用

<sql id="if-title-author">
        <if test="title !=null">
            title=#{title}
        </if>
        <if test="author!=null">
            and  author= #{author}
        </if>
    </sql>

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

注意事项:

  • 最好基于单表来定义SQL片段
  • 不要存在where标签

foreach

image-20210328221500146

select * from user where 1=1 and (id=1 or id=2 or id=3)

改造为:

select * from user where 1=1 and 

  <foreach item="id" collection="list"
      open="(" separator="or" close=")">
        #{id}
  </foreach>
  
(id=1 or id=2 or id=3)

查询测试:

image-20210328222032400

//查询1-3号记录的博客
    List<Blog> queryBlogForeach(Map map);

<!--    select * from user where 1=1 and (id=1 or id=2 or id=3)
-->
    <select id="queryBlogForeach" parameterType="map" resultType="blog">
        select  * from  mybatis.blog
        <where>
            <foreach collection="ids" item="id"  open="and (" close=")" separator="or">
                id=#{id}
            </foreach>
        </where>

    </select>
	@Test
    public  void  queryBlogForeach(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

        HashMap hashMap = new HashMap();
        ArrayList<Integer> ids = new ArrayList<>();
        ids.add(1);
        ids.add(2);

        hashMap.put("ids",ids);
        List<Blog> blogs = mapper.queryBlogForeach(hashMap);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
        sqlSession.close();
    }

image-20210328223759403

动态sql就是在拼接sql语句,我们只要保证sql正确性,按照sql的格式,去排列组合就可以了

建议:

先在mysql中写出完整的sql,再对应的去修改成为动态sql实现通用

13,缓存

查询:;连接数据库,耗资源。

一次查询的结果,给他暂存一个可以直接取到的地方–>内存:缓存

再次查询相同数据的时候没直接走缓存,就不用走数据库了。

image-20210329202417892

image-20210329202626391

一级缓存

image-20210329203736097

测试步骤:

1,开启日志

 <settings>
        <setting name="logImpl" value="LOG4J"/>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

2,测试在一个session中查询两次同一记录

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

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

        System.out.println("=================");

        User user2 = mapper.queryUserById(1);
        System.out.println(user2);

        sqlSession.close();
    }

3,查看日志输出

image-20210329204754782

失效情况:

1,查询两次不相同的记录

image-20210329205128562

2,更新(增删改)数据表

3,查询不同的Mapper.xml

4,手动清理缓存

sqlSession.clearCache();

image-20210329205606824

小结:一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段!

二级缓存

image-20210329210123952

image-20210329210009467

步骤:

1,开启全局缓存

image-20210329210227139

<!--  显示开启全局缓存-->
 <setting name="cacheEnabled" value="true"/>

2,在要使用二级缓存的mapper中开启

<!--    在当前mapper.xml中使用二级缓存-->
    <cache
            eviction="FIFO"
            flushInterval="60000"
            size="512"
            readOnly="true"/>

也可以自定义参数

3,测试

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

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        UserMapper mapper2 = sqlSession.getMapper(UserMapper.class);

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

        System.out.println("=================");

        User user2 = mapper2.queryUserById(1);
        System.out.println(user2);

        sqlSession.close();
        sqlSession2.close();
    }

image-20210329210928636

注意:mapper.xml中配置不写内容时,会报错

org.apache.ibatis.cache.CacheException: Error serializing object. Cause: java.io.NotSerializableException: pojo.User

<cache/>

image-20210329211258163

这时需要将实体类序列化!!

image-20210329211514840

小结:

  • 只要开启了二级缓存,在同一个mapper下就有效
  • 所有的数据都会先放在一级缓存中
  • 只有当会话提交,或者关闭的时候,才会提交到二级缓存中

缓存原理

image-20210329212132015

自义定缓存-ehcache(了解)

EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。

使用:

先导包

<dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-ehcache</artifactId>
    <version>1.1.0</version>
</dependency>

  <cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

ehcache.xml

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

注:本笔记于b站up主“遇见狂神说”
https://www.bilibili.com/video/BV1NE411Q7Nx
处学习记录,仅供学习与参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值