Mybatis

Mybatis3

环境:

  • JDK13.0.2
  • Mysql 8.0.21
  • Maven 3.6.3
  • IDEA2020.2

SSM框架(配置文件的):主看官方文档Mybatis3

1.简介

1.1 什么是Mybatis

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

  • Maven仓库:

    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.3</version>
    </dependency>
    
  • Github:https://github.com/mybatis/mybatis-3/releases

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

1.2持久化

数据持久化

  • 持久化就是将程序的数据在持久状态和瞬时状态转化的过程
  • 内存:断电即失
  • 数据库(JDBC),io文件持久化

对象要求你能持久,你不持久对象就换个持久的

1.3持久层

Dao层,Service层,Controller层···

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

2.第一个Mybatis程序

思路:搭建环境–>导入Mybatis–>编写代码–>测试! 学任何新东西都要按照这个流程走

2.1搭建环境

搭建数据库

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,'SCQ','4jrj3k'),
(3,'wmllk','oodkka')

新建项目(注意:一定要改:由于idea在创建新maven项目时候会自动使用自己C盘的原配置,但我们要放进自己的仓库和使用自己的配置,修改配置请看此链接IDEA修改maven地址配置

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

    • image-20210127194654203

      这里不勾选

    • image-20210127194813901

      此处按自己信息填写即可

  2. 删除src目录

  3. 导入maven依赖

    <dependencies>
    <!--    mysql驱动-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.21</version>
            </dependency>
    <!--   mybatis-->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.3</version>
            </dependency>
    <!--    junit-->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
                <scope>test</scope>
            </dependency>
        </dependencies>
    

2.2创建一个模块

  • 编写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核心配置文件-->
    <configuration>
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=true&amp;serverTimezone=GMT%2B8"/>
                    <property name="username" value="root"/>
                    <property name="password" value="514322"/>
                </dataSource>
            </environment>
        </environments>
    </configuration>
    
  • 编写mybatis工具类

    //工具类 SqlSessionFactory
    public class MybatisUtils {
    
        private static SqlSessionFactory sqlSessionFactory;
    
        static {
            try {
                //使用Mybatis获取SqlSessionFactory对象
                String resource = "mybatis-config.xml";
                InputStream inputStream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
        // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
        // 你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。
        public static SqlSession getSqlSession(){
            return sqlSessionFactory.openSession();
        }
        //学会经常优化代码,使其更加简洁,如源代码:
        //    SqlSession sqlSession = sqlSessionFactory.openSession();
        //        return sqlSession;
    

2.3编写代码

  • 实体类

    //实体类
    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接口

    public interface UserDao {
        List<User> getUserList();
    }
    
  • 接口实现类由原来的UserDaoImpl转变为一个Mapper配置文件

    <?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">
    <!--命名空间(Namespaces)绑定一个Dao/Mapper接口-->
    <mapper namespace="com.sun.dao.UserDao">
        <select id="getUserList" resultType="com.sun.pojo.User">
            select * from mybatis.user
        </select>
    </mapper>
    

    id对应的是接口里面声明的方法名,结果类别就是接口中声明的泛型

2.4测试

注意点:org.apache.ibatis.binding.BindingException: Type interface com.sun.dao.UserDao is not known to the MapperRegistry.

MapperRegistry是什么?

核心配置文件中注册mappers

  • junit测试(test文件的路径尽量与上面代码的结构一致,符合代码规范)

    public class UserDaoTest {
    
        @Test
        public void test(){
    
            //第一步:获取sqlSession对象
            SqlSession sqlSession = MybatisUtils.getSqlSession();
    
            //第二步:方法一:getMapper
            UserDao userDao = sqlSession.getMapper(UserDao.class);
            List<User> userList = userDao.getUserList();
    
            for (User user : userList) {
                System.out.println(user);
            }
    
            //关闭sqlSession
            sqlSession.close();
        }
    }
    

    可能遇到的问题:

    1. 配置文件没有注册
    2. 绑定接口错误
    3. 方法名不对
    4. 返回类型不对
    5. Maven导出资源问题

    注意在核心配置文件里加入如下过滤,防止出现异常

    <!--    在build中配置resources,来防止我们资源导出失败的问题-->
        <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>false</filtering>
                </resource>
            </resources>
        </build>
    

3.CRUD

1.namespace

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

2.select

选择,查询语句

  • id:对应的namespace中的方法名;
  • resultType:sql语句执行的返回值!
  • parameterType:参数类型!
  1. 编写接口

    //根据ID查询用户
    User getUserById(int id);
    
  2. 编写对应的mapper中的sql语句

    <select id="getUserById" resultType="com.sun.pojo.User" parameterType="int">
        select * from mybatis.user where id = #{id}
    </select>
    
  3. 测试

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

3.Insert

<insert id="addUser" parameterType="com.sun.pojo.User">
    insert into mybatis.user (id, name, pwd) VALUES (#{id},#{name},#{pwd});
</insert>

4.Update

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

5.Delete

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

注意点!!!!!!!!增删改需要提交事务

sqlSession.commit();

6.万能Map

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

int addUser2(Map<String,Object> map);
<!--传递map中的key-->
<insert id="addUser2" parameterType="map">
    insert into mybatis.user (id, pwd) VALUES (#{userid},#{password});
</insert>
@Test
public void addUser2(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    HashMap<String, Object> map = new HashMap<>();
    map.put("userid", "5");
    map.put("username", "吼哒");
    map.put("password", "5f3536");
    mapper.addUser2(map);
    sqlSession.commit();
    sqlSession.close();
}

Map传递参数,直接在sql中取出key即可!parameterType=“map”

对象传递参数,直接在sql中取对象的属性即可!parameterType=“Object”

只有一个基本类型参数的情况下,可以在sql中直接取到!

多个参数用map,或者注解

7.模糊查询

//模糊查询
List<User> getUserLike(String value);
<select id="getUserLike" resultType="com.sun.pojo.User">
    select * from mybatis.user where name like #{value}
</select>
@Test
public void getUserLike(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    List<User> userList = mapper.getUserLike("%李%");
    for (User user : userList) {
        System.out.println(user);
    }
    sqlSession.close();
}

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

在sql拼接中使用通配符!

4.配置解析

1.核心配置文件

  • mybatis-config.xml
  • Mybatis的配置文件包含了会深深影响Mybatis行为的设置和属性信息
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)

2.环境配置(environments)

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

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

学会使用配置多套环境!如配置oracle的数据库环境等,应对不同开发场景,使用的时候在default里选就行了

image-20210128224501409

Mybatis默认的事务管理器就是JDBC(还有一个是Managed,但是基本不用),数据库连接池:POOLED

3.属性(properties)

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

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

编写一个配置为文件db.properties

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
username=root
password=514322

在核心配置文件中引入

<properties resource="db.properties">
        <property name="username" value="root"/>
        <property name="password" value="514322"/>
</properties>
  • 可以直接引入外部文件
  • 可以在其中增加一些属性配置
  • 如果两个文件有同一个字段,如同时写了数据库的账号和密码,则系统会优先使用外部配置文件!

4.类型别名(typeAliases)

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

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

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

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

在实体类比较小的时候使用第一种方式来取别名,在实体类比较大的时候建议使用第二种!

第一种可以DIY,第二种起别名不是很方便,需要在实体类上添加注解,如下:

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

image-20210129100157116

5.设置

常见的如下:

image-20210129101107739

image-20210129101222322

学了spring之后这些就不用了

6.映射器(mappers)

MapperRegistry:注册绑定我们的Mapper文件(官网有四种,但不需要全部会用)

方式一:使用相对于类路径的资源引用

<!--每一个Mapper.xml都需要在Mybatis的核心配置文件中注册-->
    <mappers>
        <mapper resource="com/sun/dao/UserMapper.xml"/>
    </mappers>

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

<mappers>
    <!--        <mapper resource="com/sun/dao/UserMapper.xml"/>-->
    <mapper class="com.sun.dao.UserMapper"/>
</mappers>

注意点:

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

7.生命周期和作用域

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

SqlSessionFactoryBuilder:

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

SqlSessionFactory:

  • 可以认为是数据库连接池,创建后就一直存在
  • 没有任何理由丢弃他或重新创建另一个实例
  • 最简单的就是使用单例模式或者静态单例模式
  • SqlSessionFactory的最佳作用域是应用作用域

SqlSession:

  • 每个线程都应该有自己的SqlSession实例

  • 连接到连接池的一个请求

  • 用完后需要马上关闭

    sqlSession.close();
    

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

1.问题

数据库中的字段

image-20210129111123573

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

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

测试出现问题:

image-20210129113153931

// select * from mybatis.user where id = #{id}
// 类型处理器
// select id,name,pwd from mybatis.user where id = #{id}

解决方法:

  • 起别名

    <select id="getUserById" resultType="com.sun.pojo.User" parameterType="int">
        select id, name, pwd as password from mybatis.user where id = #{id}
    </select>
    

2.resultMap

结果集映射

id  name  pwd 
id  name  password
<!--结果集映射-->
<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="getUserById" resultMap="UserMap" parameterType="int">
    select * from mybatis.user where id = #{id}
</select>
  • resultMap 元素是 MyBatis 中最重要最强大的元素。

  • ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。

  • 你会发现上面的例子没有一个需要显式配置 ResultMap,这就是 ResultMap 的优秀之处——你完全可以不用显式地配置它们。

    也就是上面的resultMap中的id和name都用写,只需要写需要改变的就行了

  • ==如果这个世界总是这么简单就好了。==后面会有更加复杂的数据库,所以这类简单的其实也不是很需要用到这个知识

6.日志

1.日志工厂

如果一个数据库操作出现了异常,需要排错,所以用日志

image-20210129160739890

重点:LOG4J,STDOUT_LOGGING

在Mybatis中具体使用哪一个,在设置中设定!

STDOUT_LOGGING标准日志输出

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

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

image-20210129162304760

2.LOG4J

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

    <!-- https://mvnrepository.com/artifact/log4j/log4j -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    
  2. 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/sun.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-20210129202415935

简单使用

  1. 在要使用log4j 的类中,导入包

    import org.apache.log4j.Logger;
    
  2. 日志对象,参数为当前类的class

    static Logger logger = Logger.getLogger(UserMapperTest.class);
    
  3. 日志级别

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

7.分页

思考:为什么要分页?

  • 减少数据的处理量

1.使用Limit分页(本质还是sql)

使用Limit分页

select * from user limit startIndex,pageSize;
image-20210129210859318

这就代表从位置为0的地方开始查,查两个数

image-20210129211154237

这个3就是显示个数,前面默认为0

使用Mybatis实现分页,核心是SQL

  1. 接口

    //分页
    List<User> getUserByLimit(Map<String,Integer> map);
    
  2. Mapper.xml

    <!--    分页-->
    <select id="getUserByLimit" parameterType="map" resultMap="UserMap">
        select * from mybatis.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", 2);
            List<User> userList = mapper.getUserByLimit(map);
            for (User user : userList) {
                System.out.println(user);
            }
            sqlSession.close();
        }
    

2.RowBounds分页

不再使用SQL实现分页

  1. 接口

    //RowBounds分页(用的很少)
    List<User> getUserByRowBounds();
    
  2. mapper.xml

    <select id="getUserByRowBounds" resultMap="UserMap">
        select * from mybatis.user
    </select>
    
  3. 测试

    @Test
    public void getUserByRowBounds(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
    
        //RowBounds实现
        RowBounds rowBounds = new RowBounds(1, 2);
    
        //通过Java代码实现分页
        List<User> userList = sqlSession.selectList("com.sun.dao.UserMapper.getUserByRowBounds",null,rowBounds);
    
        for (User user : userList) {
            System.out.println(user);
        }
    
        sqlSession.close();
    
    }
    

8.使用注解开发

1.面向接口编程

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

根本原因:解耦,提高复用,分层开发时,上层不用考虑具体的实现,所有开发人员共同遵守相同的标准,使得开发效率更高,规范性更好

三个面向的区别:

  • 是指,我们考虑问题时,以对象为单位,考虑它的属性及方法
  • 面向过程是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现
  • 面向interface编程,原意是指面向抽象协议编程,实现者在实现时要严格按协议来办。面向对象编程是指面向抽象和具象。抽象和具象是矛盾的统一体,不可能只有抽象没有具象。一般懂得抽象的人都明白这个道理。 但有的人只知具象却不知抽象为何物。  所以只有interface没有实现,或只有实现而没有interface者是没有用的,反OO的。

2.使用注解开发

  1. 注解在接口上实现

    @Select("select * from user")
    List<User> getUsers();
    
  2. 然后在核心配置文件中绑定接口

    <!--    绑定接口-->
    <mappers>
        <mapper class="com.sun.dao.UserMapper"/>
    </mappers>
    
  3. 测试

本质:反射机制实现

底层:动态代理!

注:java SE基础重新看一看

MyBatis详细执行流程

未命名文件

3.注解的CRUD

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

image-20210130104201933

写测试类或实现类的时候就**不需要再去写sqlSession.commit( );**了

方法存在多个参数时,加上@Param标签

image-20210130104129773

编写接口,增加注解

public interface UserMapper {

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

    //方法存在多个参数时,所有的参数前面必须加上@Param(" ")注解
    @Select("select * from user where id = #{id}")
    User getUserById(@Param("id") int id);

    @Insert("insert into user(id,name,pwd) values (#{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(int id);
}

测试类

重点注意:必须记得把mapper接口注册到核心文件中!!!!!!!!

关于@Param()注解

  • 基本类型的参数或者String类型,需要加上
  • 引用类型不需要加
  • 如果只有一个基本类型的话,可以忽略,但保险起见还是加上
  • 在SQL中引用的就是在@Param(" ")中设定的属性名

9.Lombok

使用步骤:

  1. IDEA安装Lombok插件

  2. Maven导入jar包

  3. 在实体类上写注解

    @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
    

    常用:

    @Data:直接生成无参构造、get、set、toString、hashcode、equals
    @AllArgsConstructor 有参构造
    @NoArgsConstructor  无参构造
    @EqualsAndHashCode
    @ToString
    

10.多对一处理

多对一:

image-20210131102344656
  • 多个学生对应一个老师
  • 对于学生而言,关联----多个学生关联一个老师 多对一=
  • 对于老师而言,集合----一个老师有很多学生 一对多

sql:

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. 测试查询是否能够成功

按照查询嵌套处理:

<!--    思路:
            1.查询所有学生信息
            2.根据查询得到的学生的tid,寻找响应的老师
-->

<select id="getStudent" resultMap="StudentTeacher">
    select * from mybatis.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 mybatis.teacher where id = #{id};
</select>

按照结果嵌套处理:

<!--    按照结果嵌套查询-->
<select id="getStudent2" resultMap="StudentTeacher2">
    select s.id sid,s.name sname,t.name tname from mybatis.student s,mybatis.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>

回顾MySQL多对一查询方式:

  • 子查询
  • 联表查询

平时多看mysql的常见命令

11.一对多处理

比如一个老师拥有多个学生。

对于老师来说就是一对多的关系

环境搭建

和之前一样 平时多练搭建环境

实体类:

@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;
}

按照结果嵌套处理

<!--按结果嵌套查询-->
<select id="getTeacherAndStudent" resultMap="TeacherStudent">
    select s.id sid,s.name sname,t.name tname,t.id tid
    from mybatis.teacher t,mybatis.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"/>
    <!--        集合用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>

按照查询嵌套处理

<select id="getTeacherAndStudent2" resultMap="TeacherStudent2">
    select * from mybatis.teacher where id = #{tid}
</select>
<resultMap id="TeacherStudent2" type="Teacher">
    <collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
    select * from mybatis.student where tid = #{tid}
</select>

注意,可能出现这个问题,按照以下方式检查就行

image-20210201195314698

总结:

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

注意点:

  • 保证sql的可读性,尽量保证通俗易懂
  • 注意一对多和多对一的关系,属性名和字段名对应问题
  • 经常用日志和debug来检查

12.动态SQL

什么是动态SQL:动态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 

注意,有时候写@Test注解无法使用的时候,往往是pom.xml文件中的依赖的限制了范围,可以删掉范围就为全局了,或者就在目录的test文件下写test文件(Test文件名不要写Test!!!!!!重名了容易报错),会比较规范

创建一个基础工程

  1. 导包

  2. 编写配置文件

  3. 编写实体类

    @Data
    public class Blog {
        private String id;
        private String title;
        private String author;
        private Date createTime;
        private int views;
    }
    //Java里的时间用util.Date而不是sql里的Date包,注意不要导错
    
  4. 编写实体类对应的Mapper接口和Mapper.xml

    public interface BlogMapper {
        //插入数据
        int addBlog(Blog blog);
    }
    
    <mapper namespace="com.sun.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>
    

课程P22的测试语句:

public class MyTest {

    @Test
    public void addBlogTest() {
        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.addBlog(blog);

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

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

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

        sqlSession.close();
    }
}

IF

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

choose、when、otherwise

<!--    这个相当于switch case的操作-->
<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 * from mybatis.blog
<where>
    <if test="title != null">
        and title = #{title}
    </if>
    <if test="author != null">
        and author = #{author}
    </if>
</where>
<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>

SQL片段

有时候,我们可能会将一些功能的部分抽取出来,方便复用

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

    <sql id="if-title-author">
        <if test="title != null">
            and title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </sql>
    
  2. 在需要使用的地方使用include标签引用

    <where>
        <include refid="if-title-author">
    
        </include>
    </where>
    

    最好基于单表定义SQL片段

    不要存在where标签

foreach

<!--    我们现在传递一个万能map,,这个map中可以存在一个集合!
        需要拼接的SQL语句:
        select * from mybatis.blog 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>

image-20210202150710118

官方文档内容平时多看多理解

image-20210202101525322

image-20210202101555497image-20210202101621601

image-20210202101700848

image-20210202105145410

动态SQL就是在拼接SQL,保证正确的语句后进行拆分修改成正确的语句=

13.缓存

1.简介

查询:  连接数据库 , 耗费资源!
	一次查询的结果可以暂存到一个可以直接读取的地方  ---> 内存:缓存
	
	我们再次查询相同数据的时候,直接走缓存,而不用去查数据库

1.什么是缓存【Cache】?

  • 存在内存中的临时数据
  • 将用户查询的数据直接放在缓存中,类似于迅雷云盘和百度网盘的工作原理;可以提高查询效率,解决高并发问题

2.为什么使用缓存?

  • 减少和数据库的交互次数,减少系统开销,提高系统效率

3.什么样的数据使用缓存比较好?

  • 经常查询且不会经常改变的数据

2.Mybatis缓存

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

3.一级缓存

  1. 开启日志!

  2. 测试在一个Session中查询两次相同记录

  3. 查看日志输出

    image-20210202190818697

缓存失效的情况:

  1. 查询不同的东西

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

  3. 查询不同的mapper

  4. 手动清理缓存的时候

    sqlSession.clearCache();
    

小结:一级缓存默认开启,只在一次Session中有效(即在close前),也关不掉

一级缓存相当于map

4.二级缓存

官方文档内容:

image-20210202191807979

二级缓存基于namspace级别,一个命名空间对应一个二级缓存

就是在sqlsesion.close以后一级缓存已经没有了,但是可以通过二级缓存来再次查询到

步骤:

  1. 开启全局缓存

    <!--        开启全局缓存-->
    <setting name="cacheEnabled" value="true"/>
    
  2. 在要使用二级缓存的mapper.xml文件中开启

    <cache/>
    

    也可以自定义一些配置,像官方文档那样

    <cache
            eviction="FIFO"
            flushInterval="60000"
            size="512"
            readOnly="true"/>
    
  3. 测试后

    我们需要将实体类序列化,否则会报错

5.缓存原理

image-20210202195412517

6.自定义缓存-echcache

EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,主要面向通用缓存

仅仅了解,之后要学redis

13.缓存

1.简介

查询:  连接数据库 , 耗费资源!
	一次查询的结果可以暂存到一个可以直接读取的地方  ---> 内存:缓存
	
	我们再次查询相同数据的时候,直接走缓存,而不用去查数据库

1.什么是缓存【Cache】?

  • 存在内存中的临时数据
  • 将用户查询的数据直接放在缓存中,类似于迅雷云盘和百度网盘的工作原理;可以提高查询效率,解决高并发问题

2.为什么使用缓存?

  • 减少和数据库的交互次数,减少系统开销,提高系统效率

3.什么样的数据使用缓存比较好?

  • 经常查询且不会经常改变的数据

2.Mybatis缓存

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

3.一级缓存

  1. 开启日志!

  2. 测试在一个Session中查询两次相同记录

  3. 查看日志输出

    [外链图片转存中…(img-cAqs6qeL-1612268827431)]

缓存失效的情况:

  1. 查询不同的东西

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

  3. 查询不同的mapper

  4. 手动清理缓存的时候

    sqlSession.clearCache();
    

小结:一级缓存默认开启,只在一次Session中有效(即在close前),也关不掉

一级缓存相当于map

4.二级缓存

官方文档内容:

[外链图片转存中…(img-rpcxXAPH-1612268827432)]

二级缓存基于namspace级别,一个命名空间对应一个二级缓存

就是在sqlsesion.close以后一级缓存已经没有了,但是可以通过二级缓存来再次查询到

步骤:

  1. 开启全局缓存

    <!--        开启全局缓存-->
    <setting name="cacheEnabled" value="true"/>
    
  2. 在要使用二级缓存的mapper.xml文件中开启

    <cache/>
    

    也可以自定义一些配置,像官方文档那样

    <cache
            eviction="FIFO"
            flushInterval="60000"
            size="512"
            readOnly="true"/>
    
  3. 测试后

    我们需要将实体类序列化,否则会报错

5.缓存原理

[外链图片转存中…(img-GrDvKqxm-1612268827433)]

6.自定义缓存-echcache

EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,主要面向通用缓存

仅仅了解,之后要学redis

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值