IDEA中MyBatis使用记录

1 篇文章 0 订阅
1 篇文章 0 订阅


按照自我编程学习顺序记录
学习视频地址

【狂神说Java】Mybatis最新完整教程IDEA版通俗易懂 https://www.bilibili.com/video/BV1NE411Q7Nx
以下内容仅作自我复习查看使用

配置Mybatis

1.1、下载jar包

  • maven仓库
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.2</version>
</dependency>  
  • Github:https://github.com/mybatis/mybatis-3/releases
  • 中文文档: https://mybatis.org/mybatis-3/zh/index.html

1.2、搭建环境

  1. IDEA中创建一个普通的IDEA项目
    在这里插入图片描述
  2. 加载需要的maven依赖
  • 此处数据库为mysql
<?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.syk</groupId>
    <artifactId>mybatis-study</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>mybatis-01</module>
    </modules>

<dependencies>
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.20</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13</version>
        <scope>test</scope>
    </dependency>
</dependencies>
<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>

</project>
  • 此处数据库为sqlserver
<?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.syk</groupId>
    <artifactId>mybatis-study-02</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>mybatis-02</module>
    </modules>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.20</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>

        </dependency>

        <!-- https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc -->
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <version>8.3.0.jre8-preview</version>
        </dependency>

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

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

    </build>

</project>
  1. mybatis-config.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="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="org/mybatis/example/BlogMapper.xml"/>
  </mappers>
</configuration>
  1. Mapper.xml
<?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="org.mybatis.example.BlogMapper">
  <select id="selectBlog" resultType="Blog">
    select * from Blog where id = #{id}
  </select>
</mapper>
  1. MyBatisUtils 类,基础类
package com.syk.util;

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 {
    public static SqlSessionFactory sqlSessionFactory = null;

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

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

1.3、排坑

  1. 报错,mapper注册错误
    可能原因:Mapper未在 mybatis-config.xml 中注册
  2. mysql数据库连接不上
  • 新的 mysql jdbc连接字符串可能要传时区
  • mysql的url写的不对
    示例:
<dataSource type="POOLED">
 	<property name="driver" value="com.mysql.jdbc.Driver"/>
	<property name="url" value="jdbc:mysql://localhost:3306/database?useUnicode=true&amp;characterEncoding=utf-8"/>
	<property name="username" value="root"/>
	<property name="password" value="123456"/>
</dataSource>
  1. sqlserver 连不上
  • 可能原因,本地1433端口没开 参考

https://www.jianshu.com/p/b99b1907d848

  • 配置文件示例
<environment id="development">
	<transactionManager type="JDBC"/>
	<dataSource type="POOLED">
		<property name="driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
		<property name="url" value="jdbc:sqlserver://localhost:1433;DatabaseName=DataBase"/>
		<property name="username" value="sa"/>
		<property name="password" value="123456"/>
	</dataSource>
</environment>
  • 还有一个巨坑
    去maven仓库找包的时候一定要注意这个包适用的 jre 的版本,也就是 jdk 的版本,sqlserver 的驱动每一个版本的包都有好几种适用的 jre 的版本,版本太高的话,项目可能解析不了 jar 包
    在这里插入图片描述
  • 找不到写的Mapper.xml,在项目pom.xml中添加,即可使在java目录下的.xml文件也被导出,因为maven项目约定大于依赖,所以其原本是不允许在java下写.xml文件和.properties文件,所以在项目导出时不会扫描java包下的这两种文件。因为其默认为在resources文件夹下。
 <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>

    </build>

使用MyBatis

4、配置解析(真正需要掌握的能力)

1、核心配置文件

  • mybatis-config.xml

  • MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。 配置文档的顶层结构如下:

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

在这里插入图片描述

2、环境配置(environments)

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

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

在这里插入图片描述
在这里插入图片描述
学会使用配置多套运行环境

Mybatis默认的事物管理器就是JDBC,连接池KPOOLED

3、属性(properties)

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

这些属性可以在外部进行配置,既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素来传递【db.properties】

  1. 编写一个数据库配置文件

    db.properties

在核心中引入
在这里插入图片描述

6、日志

6.1、日志工厂

如果一个数据库操作,出现了异常,我们需要排错,日志就是最好的助手!

曾经:sout、debug

现在:日志工厂

setting中:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZNM4grIP-1589445856157)(Mybatis-Study-02.assets/image-20200513095530974.png)]

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

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

STDOUT_LOGGING 标准日志输出

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-upRWWgCm-1589445856159)(Mybatis-Study-02.assets/image-20200513100807747.png)]

在mybatis核心文件中,配置我们的日志!

<settings>
     <!--标准的日志工厂实现-->
    <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QJfNolKg-1589445856161)(Mybatis-Study-02.assets/image-20200513100922299.png)]

6.2、Log4j

什么是 Log4j?

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

    
    
  2. log4j.properties

    #将等级为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/kuang.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 hh:mm:ss}][%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
    

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zRlvcgzD-1589445856163)(Mybatis-Study-02.assets/image-20200513102420816.png)]

  3. 配置为log4j的实现

     <setting name="logImpl" value="LOG4J"/>
    
  4. LOG4J 的使用,直接测试运行刚才的查询

简单使用

  1. 在要使用 LOG4J 的包要导入 apache 的

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

      public static Logger logger = Logger.getLogger(PersonMapperTest.class);
    

    包:

    import org.apache.log4j.Logger;
    

7、分页

为啥分页?

  • 减少数据处理量

7.1、使用Limit分页

MySql使用Limit分页

select * from tb limit startIndex,pageLimit
select * from tb limit n    --相当于[0,n]

Sqlserver分页

<select id="getPersonByLimit" resultMap="personMap" parameterType="map">
    select * from (select *,row_number() over (order by idx) no from data_person) a where <![CDATA[  a.no> #{startIndex} and a.no < = (#{startIndex}+#{pageSize})  ]]>
</select>

对于使用 > < 的语句得用 <![CDATA[ ]]> 把 加括号 包裹起来,否则认为是标签

参考:https://www.cnblogs.com/pangguoming/p/7634336.html

7.2、使用Rowbounds分页

不分数据库是什么类型的,具有一定的通用性

public interface PersonMepper {
    List<Person> getPersonByRowbounds();
}
<select id="getPersonByRowbounds" resultMap="personMap">
    select * from data_person
</select>
@Test
public void getPersonByRowboundsTest(){
    // 在代码层层面实现分页
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    RowBounds rowBounds=new RowBounds(0,8);
    PersonMepper mapper = sqlSession.getMapper(PersonMepper.class);
    Map<String,Integer> map=new HashMap<String,Integer>();
    List<Person> personList = sqlSession.selectList("com.syk.dao.PersonMepper.getPersonByRowbounds", null, rowBounds);

    for (Person person : personList) {
        System.out.println(person);
    }
    sqlSession.close();
}

核心原理:

逻辑分页

https://blog.csdn.net/qq924862077/article/details/52611848

和PageHelper性能评测:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uY20WCzw-1589445856165)(Mybatis-Study-02.assets/image-20200513131937372.png)]

https://blog.csdn.net/wangzhetianxia8/article/details/88783431

7.3、分页插件

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-bD5IGpXi-1589445856166)(Mybatis-Study-02.assets/image-20200513132810056.png)]

8、使用注解开发

8.1、面向接口编程

在这里插入图片描述

8.2、使用注解开发

  1. 注解直接在接口上实现

    package com.syk.dao;
    
    import com.syk.pojo.User;
    import org.apache.ibatis.annotations.*;
    
    import java.util.List;
    
    public interface UserMapper {
        @Select(" select * from users where id = #{id} ")
        User getUserById(@Param("id") int id);
    
        @Select(" select * from users where username like \"%\"#{username}\"%\" and  address like \"%\"#{address}\"%\" ")
        List<User> getUserList(@Param("username") String username, @Param("address") String address);
    
    /*    @Select(" select * from users where username like \"%\"#{username}\"%\" ")
        List<User> getUserList(@Param("username") String username);*/
    
    /*    @Select(" select * from users limit #{startIndex},#{pageSize} ") // 不能够使用重载,即使参数个数、类型完全不同
        List<User> getUserList(@Param("startIndex") int startIndex, @Param("pageSize") int pageSize);*/
    
        @Select(" select * from users limit #{startIndex},#{pageSize} ")
        List<User> getUserListByLimit(@Param("startIndex") int startIndex, @Param("pageSize") int pageSize);
    
        @Insert(" insert into users(id,username,password,address) values (#{id},#{username},#{password},#{address})")
        int insertUser(User user);
    
        @Update(" update users set username=#{username},password=#{password},address=#{address} where id=#{id} ")
        int updateUser(User user);
    
        @Delete(" delete from users where id=#{id} ")
        int deleteUser(@Param("id") int id);
    }
    
    
  2. 需要在核心配置文件中绑定接口!

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

本质:反射机制实现

底层:动态代理!

简单的语句可以使用注解开发,不过最好还是使用xml进行项目开发,这也是官方建议的!

代理:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OZtP3eDZ-1589445856170)(Mybatis-Study-02.assets/image-20200513134932777.png)]

Mybatis详细执行流程

自己走一遍这个流程

8.3、CRUD

我们可以在工具类创建的时候实现自动提交事务!

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

编写接口,增加注解

测试类

package com.syk.dao;

import com.syk.pojo.User;
import com.syk.utils.MybatisUtils;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class UserMapperTest {

    @Test
    public void getUserByIdTest() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.getUserById(1);
        System.out.println(user);
        sqlSession.close();
    }

    @Test
    public void getUserListTest() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.getUserList("", "");
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }

    @Test
    public void getUserListByLimitTest() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.getUserListByLimit(2, 5);
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }

    @Test
    public void insertUserTest() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int i = mapper.insertUser(new User(13, "座山雕", "123546", "天山"));
        System.out.println(i > 0 ? "插入成功" : "插入失败");
        sqlSession.close();
    }

    @Test
    public void updateUserTest() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int i = mapper.updateUser(new User(13, "3332座山雕2333", "123546", "天山"));
        System.out.println(i > 0 ? "修改成功" : "修改失败");
        sqlSession.close();
    }

    @Test
    public void deleteUserTest() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int i = mapper.deleteUser(13);
        System.out.println(i > 0 ? "删除成功" : "删除失败");
        sqlSession.close();
    }

}

【注意:必须注册绑定打破核心配置文件】

关于@Param() 注解

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

#{} ${} 区别

#{}:较为安全可以防注入,一般使用这个,就相当于 JDBC中的预编译的PrepareStatement

注(坑):

  • 使用注解开发是在interface(UserMapper)中,两个方法之间不可以使用相同的名称。即使参数的类型和数量完全不同也不行,即不能使用重载。看不了debug,根本进不去,在MybatisUtiles静态类的时候就报错了。。。

  • 测试了下,不管是使用注解不能重载,而切使用 **Mapper.xml 的方式也不能重载。

    Caused by: java.lang.IllegalArgumentException: Mapped Statements collection already contains value for com.syk.dao.PersonMepper.getPersonListByIdx. please check com/syk/dao/PersonMapper.xml and com/syk/dao/PersonMapper.xml
    

    分析了一波

    <!-- <parameterMap id="s" type="">
        <parameter property="" resultMap=""></parameter>
    </parameterMap>-->
    <select id="getPerosnList" resultMap="personMap" parameterType="map">
        select * from data_person where name like #{name} and sex = #{sex}
    </select>
    

    因为select标签使用的是 id ,所以id的意思可能就代表了唯一性,故在同一个 namespace 中方法名不能相同,即不能使用重载。

  • 在SQL语句中使用 % 的方式正确

    @Select(" select * from users where username like \"%\"#{username}\"%\" and  address like \"%\"#{address}\"%\" ")
    

9、Lombok

10、多对一处理

  • 多个学生学生对应一个老是
  • 对于学生而言,,关联… 多个学生关联一个老师【多对一】
  • 对于老师而言,集合,一个老是,很多学生【一对多】

测试环境搭建

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-u9fgzrHr-1589445856171)(Mybatis-Study-02.assets/image-20200513212354809.png)]

StudentMapper

package com.syk.dao;

import com.syk.pojo.Student;

import java.util.List;

public interface StudentMapper {
    List<Student> getStudentList();
    List<Student> getStudentList2();
}

按照查询嵌套处理

<?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.syk.dao.StudentMapper">
    <select id="getStudentList" resultMap="StudentTeacher">
        select * from student
    </select>
    <resultMap id="StudentTeacher" type="student">
        <association property="teacher" column="tid" javaType="Teacher" select="selectTeacher"></association>
    </resultMap>
    <select id="selectTeacher" resultType="teacher">
        select * from teacher where id=#{id}
    </select>
</mapper>

按照结果嵌套处理

<select id="getStudentList2" resultMap="StudentTeacher2">
    select s.id sid,s.name sname,t.id tid,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">
        <result property="id" column="tid"></result>
        <result property="name" column="tname"></result>
    </association>
</resultMap>

测试类

@Test
public void test01(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
    List<Student> studentList = mapper.getStudentList();
    for (Student student : studentList) {
        System.out.println(student);
    }
    sqlSession.close();
}

@Test
public void test02(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
    List<Student> studentList = mapper.getStudentList2();
    for (Student student : studentList) {
        System.out.println(student);
    }
    sqlSession.close();
}

11、一对多

【Teacher2】

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

【Student】

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    private int id;
    private String name;
    private Teacher teacher;
}

【Teacher2Mapper】

public interface Teacher2Mapper {
    Teacher2 getTeacher2ById(@Param("id") int id);

    Teacher2 getTeacher2ById2(@Param("id") int id);
}

按照结果嵌套处理

<select id="getTeacher2ById2" resultMap="Teacehr2Student2">
    select t.id tid,t.name tname,s.id sid,s.name sname from teacher t,student s where t.id=s.tid and t.id=#{id}
</select>
<resultMap id="Teacehr2Student2" type="teacher2">
    <result property="id" column="tid"></result>
    <result property="name" column="tname"></result>
    <collection property="students" ofType="student">
        <result property="id" column="sid"></result>
        <result property="name" column="sname"></result>
    </collection>
</resultMap>

按照查询嵌套查询

<select id="getTeacher2ById" resultMap="TeacherStudent">
    select * from teacher
</select>
<resultMap id="TeacherStudent" type="teacher2">
    <!--<result property="students" column="id" -->
    <result property="id" column="id"></result>
    <collection property="students" column="id" select="getStudents" ofType="student" javaType="ArrayList"></collection>
</resultMap>
<select id="getStudents" resultType="student">
    select * from student where tid=#{id}
</select>

注:

  1. 上面的

    <collection property="students" column="id" select="getStudents" ofType="student" javaType="ArrayList"></collection>
    </resultMap>
    

    可以替换为下面的情况。不知道是不是我用的mybatis版本比较新

    <collection property="students" column="id" select="getStudents"></collection>
    </resultMap>
    
  2. 上面的

     <result property="id" column="id"></result>
    

    不能省略,否则 Teacher2中的id取不到值为0

测试类

@Test
public void getTeacher2ByIdTest(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    Teacher2Mapper mapper1 = sqlSession.getMapper(Teacher2Mapper.class);
    Teacher2 teacher2ById = mapper1.getTeacher2ById(1);
    System.out.println(teacher2ById);
    sqlSession.close();
}
@Test
public void getTeacher2ById2Test(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    Teacher2Mapper mapper1 = sqlSession.getMapper(Teacher2Mapper.class);
    Teacher2 teacher2ById = mapper1.getTeacher2ById2(1);
    System.out.println(123); // 防止调试错误了代码
    System.out.println(teacher2ById);
    sqlSession.close();
}

小结

  1. 关联 - association 【多对一】
  2. 集合 - collection 【一对多】
  3. javaType & ofType
    1. javaType 用来指定实体类中的属性的类型
    2. ofType 用来指定映射到List或者集合中的 pojo 类型,泛型中的约束类型!

注意点:

  • 保证SQL的可读性,尽量保证通俗易懂
  • 注意一对多和多对一中,属性名和字段的问题
  • 如果问题不好排查错误,可以使用日志,建议使用LOG4J

慢SQL 1s 1000s

面师高频

  • Mysql引擎
  • InnoDB底层原理
  • 索引
  • 索引优化

12、动态sql

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

if

使用动态 SQL 最常见情景是根据条件包含 where 子句的一部分

<select id="findActiveBlogLike" resultType="Blog">
    SELECT * FROM BLOG WHERE state = ‘ACTIVE’
    <if test="title != null">
        AND title like #{title}
    </if>
    <if test="author != null and author.name != null">
        AND author_name like #{author.name}
    </if>
</select>

choose、when、otherwise

<select id="findActiveBlogLike" resultType="Blog">
    SELECT * FROM BLOG WHERE state = ‘ACTIVE’
    <choose>
        <when test="title != null">
            AND title like #{title}
        </when>
        <when test="author != null and author.name != null">
            AND author_name like #{author.name}
        </when>
        <otherwise>
            AND featured = 1
        </otherwise>
    </choose>
</select>

trim、where、set

where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。

<select id="findActiveBlogLike" resultType="Blog">
  SELECT * FROM BLOG
    <where>
        <if test="state != null">
            state = #{state}
        </if>
        <if test="title != null">
            AND title like #{title}
        </if>
        <if test="author != null and author.name != null">
            AND author_name like #{author.name}
        </if>
    </where>
</select>

如果 where 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 元素的功能。比如,和 where 元素等价的自定义 trim 元素为:

<trim prefix="WHERE" prefixOverrides="AND |OR ">
  ...<!--prefix 前缀;prefixOverrides 前缀覆盖-->
</trim>

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

<update id="updateAuthorIfNecessary">
    update Author
    <set>
        <if test="username != null">username=#{username},</if>
        <if test="password != null">password=#{password},</if>
        <if test="email != null">email=#{email},</if>
        <if test="bio != null">bio=#{bio}</if>
    </set>
    where id=#{id}
</update>
<trim prefix="SET" suffixOverrides=",">
  ...<!--prefix 前缀;suffixOverrides 后缀覆盖-->
</trim>

foreach

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

【UserMappe】

public interface UserMapper {
    List<User> getUserList(@Param("username") String username);

    List<User> getUserListByList(@Param("list") List<Integer> list);

    List<User> getUserListByList02(@Param("sslist") List<Integer> list);
}

【UserMappe.xml】

<select id="getUserListByList" resultType="user">
    select * from users
    <where>
        <foreach collection="list" item="pid" open="(" close=")" separator=",">
            #{pid}
        </foreach>
    </where>
</select>

<select id="getUserListByList02" resultType="user" parameterType="list">
    select * from users
    <where>
        <foreach collection="sslist" item="pid" open="( " close=")" separator="or">
            id = #{pid}
        </foreach>
    </where>
</select>
<!-- 
1、collection="list" 中collection 对应的值是 select 语句传参的参数名称,如果传参是Map或者对象,那么mybatis默认 参数名称就会从 Map 中的key去查找,或者从对象的属性中去查找,由于参数的名称是list,所以colletction就必须写list
2、所以第二个collection中的值为 sslist 
3、若是接口为 List<User> getUserListByList02(List<Integer> aalist);并未使用@Param("")去定义值,那么xml中的 collection 就必须为 list,不能使用 aalist,不知道为啥,不过是亲测

-->

Sql脚本片段

将一部分功能呢抽取出来,方便复用!

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-J2uV5YNh-1589445856172)(Mybatis-Study-02.assets/image-20200514094713496.png)]

注意事项:

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

总结:

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

建议:现在mysql中写出完整的SQL,保证正确性,然后再在xml中配置,实现SQL的通用。

13、缓存(了解即可)

13.1、简介

查询 : 连接数据库,耗资源
    一次查询的结果,给他暂存在一个可以直接取到的地方! -->内存:缓存
我们再次查询相同的数据的时候,直接走缓存,就不用走数据库了
  1. 什么是缓存 [ Cache ] ?
    • 存在内存中的临时数据。
    • 将用户经常查询的数据放在缓存(内存)中,用户其查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。
  2. 为什么使用缓存?
    • 减少和数据库的交互次数,减少系统开销,提高系统效率
  3. 什么样的数据能使用缓存?
    • 经常查询并且不经常改变的数据【可以使用缓存】

13.2、Mybatis缓存

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

13.3、一级缓存

缓存失效的情况:

  1. 查询不同的东西

  2. 增删改,操作,可能会改变原来的数据,所以必定会刷新缓存!

  3. 查询不同的Mapper.xml

  4. 手动清理缓存!

    sqlSession.clearCache();
    

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9nG1SqXY-1589445856176)(Mybatis-Study-02.assets/image-20200514112101694.png)]

小结:一级缓存默认是开启的,也关闭不掉,只在一次Sqlsession中有效,也就是拿到连接到关闭连接这个Sqlsession

一级缓存就是map

13.4、二级缓存

  • 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存

  • 基于namsespace级别的缓存,一个命名空间,对应一个二级缓存;

  • 工作机制

    • 一个会话查询一条数据,这个数据就会被放在当前会话中的一级缓存中;
    • 如果当前绘画关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;
    • 新的查询信息,就可以从二级缓存中获取内容;
    • 不同的mapper茶树的数据会放在自己对应的缓存(map)中

    自己推断:所以为了获取数据的安全性,最好一张表对应一个mapper,而且不要再其它mapper中修改不属于该mapper对应的表的数据。

步骤:

  1. 显示的开启全局缓存

    <setting name="cacheEnabled" value="true"/>
    
  2. 在要使用二级缓存的Mapper中开启

    <!--在当前Mapper.xml中使用二级缓存-->
    <cache />
    

    也可以自定义参数

    <cache
      eviction="FIFO"
      flushInterval="60000"
      size="512"
      readOnly="true"/>
    
    
    LRU – 最近最少使用:移除最长时间不被使用的对象。
    FIFO – 先进先出:按对象进入缓存的顺序来移除它们。
    SOFT – 软引用:基于垃圾回收器状态和软引用规则移除对象。
    WEAK – 弱引用:更积极地基于垃圾收集器状态和弱引用规则移除对象。
    
    Mybatis默认的清除策略是 LRU。
    
  3. 测试

    1. 问题:我们需要将实体类序列化!否则就会报错!
    2. 因为在缓存中没有使用FIFO的策略
    3. 弹幕大佬:序列化是深拷贝,所以反序列化后的对象和元对象不是同一个对象,故hashcode不一样

一级缓存、二级缓存小结

  • 只要在同一个Mapper下就有效
  • 所有的数据都会先放在一级缓存中;
  • 只有当会话提交,过着关闭的时候,才会提交到二级缓存中;
  • 弹幕大佬:前面的实体只是数据库数据的映射,原本还是在数据库或者一级缓存中;序列化是因为实体类在二级缓存中,所以需要序列化处理才能方便查找;

13.5、缓存原理

架构图

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xWf7x4nv-1589445856177)(Mybatis-Study-02.assets/image-20200514144300707.png)]

开启了二级缓存后的查询顺序为

用户 -------> 二级缓存查询------------->一级缓存查询------------>数据库查询

sqlSession先关闭,mapper2后查询:

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

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

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

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

    sqlSession2.close();
    System.out.println("----------------------------------------");
    System.out.println(user==user2);
}

输出结果:

Created connection 282496973.
Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@10d68fcd]
==>  Preparing: select * from users where id=? 
==> Parameters: 1(Integer)
<==    Columns: id, username, password, address
<==        Row: 1, admin, 123456, 传奇人间
<==      Total: 1
User(id=1, userName=admin, password=123456, address=传奇人间)
Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@10d68fcd]
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@10d68fcd]
Returned connection 282496973 to pool.
======================================
Cache Hit Ratio [com.syk.dao.UserMapper]: 0.5
User(id=1, userName=admin, password=123456, address=传奇人间)
----------------------------------------
false

mapper2先查询,sqlSession后关闭:

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

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

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



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

    sqlSession.close();
    System.out.println("======================================");
    sqlSession2.close();
    System.out.println("----------------------------------------");
    System.out.println(user==user2);
}

结果:

Created connection 282496973.
Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@10d68fcd]
==>  Preparing: select * from users where id=? 
==> Parameters: 1(Integer)
<==    Columns: id, username, password, address
<==        Row: 1, admin, 123456, 传奇人间
<==      Total: 1
User(id=1, userName=admin, password=123456, address=传奇人间)
Cache Hit Ratio [com.syk.dao.UserMapper]: 0.0
Opening JDBC Connection
Created connection 1311146128.
Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@4e268090]
==>  Preparing: select * from users where id=? 
==> Parameters: 1(Integer)
<==    Columns: id, username, password, address
<==        Row: 1, admin, 123456, 传奇人间
<==      Total: 1
User(id=1, userName=admin, password=123456, address=传奇人间)
Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@10d68fcd]
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@10d68fcd]
Returned connection 282496973 to pool.
======================================
Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@4e268090]
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@4e268090]
Returned connection 1311146128 to pool.
----------------------------------------
false

说明了,不管是那个sqlsession在查询前都会先去看二级缓存中是否存在

在Mapper.xml中

select 标签存在  useCache(是否使用缓存)  flushCache(是否刷新缓存) 两个属性
update\delete\insert 只存在 flushCache 一个属性
用于sql调优

13.6、自定义缓存- ehcache

Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器。

要在程序中使用,先导包!

ehcache配置文件
版本1

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
    <!-- 磁盘保存路径 -->
    <diskStore path="out/mybatis_cache" />

    <defaultCache
            maxElementsInMemory="1"
            maxElementsOnDisk="10000000"
            eternal="false"
            overflowToDisk="true"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
    </defaultCache>
</ehcache>

        <!--
        属性说明:
        l diskStore:指定数据在磁盘中的存储位置。
        l defaultCache:当借助CacheManager.add("demoCache")创建Cache时,EhCache便会采用<defalutCache/>指定的的管理策略

        以下属性是必须的:
        l maxElementsInMemory - 在内存中缓存的element的最大数目
        l maxElementsOnDisk - 在磁盘上缓存的element的最大数目,若是0表示无穷大
        l eternal - 设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断
        l overflowToDisk - 设定当内存缓存溢出的时候是否将过期的element缓存到磁盘上

        以下属性是可选的:
        l timeToIdleSeconds - 当缓存在EhCache中的数据前后两次访问的时间超过timeToIdleSeconds的属性取值时,这些数据便会删除,默认值是0,也就是可闲置时间无穷大
        l timeToLiveSeconds - 缓存element的有效生命期,默认是0.,也就是element存活时间无穷大
         diskSpoolBufferSizeMB 这个参数设置DiskStore(磁盘缓存)的缓存区大小.默认是30MB.每个Cache都应该有自己的一个缓冲区.
        l diskPersistent - 在VM重启的时候是否启用磁盘保存EhCache中的数据,默认是false。
        l diskExpiryThreadIntervalSeconds - 磁盘缓存的清理线程运行间隔,默认是120秒。每个120s,相应的线程会进行一次EhCache中数据的清理工作
        l memoryStoreEvictionPolicy - 当内存缓存达到最大,有新的element加入的时候, 移除缓存中element的策略。默认是LRU(最近最少使用),可选的有LFU(最不常使用)和FIFO(先进先出)
         -->


<!--狂神视频中的配置文件

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值