MyBatis学习

MyBatis

1、简介

1.1什么是MyBatis

1.2、持久化

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

为什么需要持久化:1.有一些对象不能让它丢掉 2.内存贵

1.3、持久层

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

1.4、为什么需要MyBatis

  • 方便
  • 传统JDBC代码复杂,简化。框架。自动化。
  • 不用MyBatis也可以。更容易上手。
  • 优点
    • 简单易学,灵活,sql和代码分离,提高可维护性
    • 提供映射标签,支持对象与数据库的orm字段关系映射
    • 提供对象关系映射标签,支持对象关系组件维护
    • 提供xml标签,支持编写动态sql

2、第一个MyBatis程序

搭建环境->导入MyBatis->编写代码->测试

2.1、搭建环境

2.2、创建一个模块

  • 编写一个mybatis核心配置文件

    <?xml version="1.0" encoding="utf-8" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybaits.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
    
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=UTF-8&amp;useSSL=false"/>
                    <property name="username" value="root"/>
                    <property name="password" value="123456"/>
                </dataSource>
            </environment>
    
        </environments>
    
    </configuration>
    
  • 编写mybatis工具类

    package com.rtt.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;
    
    //工具类 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命令所需的方法
        public static SqlSession getSqlSession(){
            return sqlSessionFactory.openSession();
        }
    }
    
    

2.3、编写代码

  • 实体类

    package com.rtt.pojo;
    //实体类
    public class User {
        private int id;
        private int name;
        private int pwd;
    
        public User() {
        }
    
        public User(int id, int name, int pwd) {
            this.id = id;
            this.name = name;
            this.pwd = pwd;
        }
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public int getName() {
            return name;
        }
    
        public void setName(int name) {
            this.name = name;
        }
    
        public int getPwd() {
            return pwd;
        }
    
        public void setPwd(int pwd) {
            this.pwd = pwd;
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name=" + name +
                    ", pwd=" + pwd +
                    '}';
        }
    }
     
    
  • Dao接口

    public interface UserDao {
        List<User> getUserList();
    }
    
  • 接口实现类

    <?xml version="1.0" encoding="utf-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybaits.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <!--namespace =绑定一个对应的Dao/Mapper接口-->
    <mapper namespace="com.rtt.dao.UserDao">
        <select id="getUserList" resultType="com.rtt.pojo.User">
            select * from mybatis.user;
        </select>
    </mapper>
    

2.4、测试

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

MapperRegistry:每一个Mapper.xml文件都要在Mybatis核心配置文件中注册

  • junit

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

3、CRUD

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

2、select

选择,查询

  • id:对应的namespace方法名

  • resultType:sql语句执行的返回值

  • parameterType:参数类型

  1. 编写接口

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

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

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

3、insert

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

4、update

    <update id="updateUser" parameterType="com.rtt.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>

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


4、配置解析

1、核心配置文件

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

2、环境配置

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

不过,尽管可以配置多种环境,但每个SqlSessionFactory只能选择一种环境

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

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

3、属性

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

这些属性都是可外部配置且动态替换的,既可以在典型的java属性文件中配置,亦可通过properties元素的子元素来传递【db.properties】

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8&useSSL=false
name=root
password=123456

在核心配置文件中引入

<!--    引入外部配置文件-->
    <properties resource="db.properties"/>

4、别名

  • 类型别名是为java类型设置一个短的名字
  • 存在的意义仅在于用来减少类完全限定名的冗余
<!--    给实体类起别名-->
    <typeAliases>
        <typeAlias type="com.rtt.pojo.User" alias="User"/>
    </typeAliases>

    <typeAliases>
<!--也可以指定包名,会搜索包名下的javabean-->
        <package name="com.rtt.pojo"/>
    </typeAliases>

接口和它的mapper配置文件必须同名且在同一个包下


5、日志

5.1日志工厂

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

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

5.2、Log4j

  • 可以控制日志信息输送的目的的是控制台,文件,GUI组件

  • 可以控制每一条日志输出格式

  • 通过一个配置文件来灵活配置,不需要修改应用代码

  1. 先导包
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
  1. log4j.properties

    #将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
    log4j.rootLogger=DEBUG,console,file
    
    #控制台输出的相关设置
    log4j.appender.console = org.apache.log4j.ConsoleAppender
    log4j.appender.console.Target = System.out
    log4j.appender.console.Threshold=DEBUG
    log4j.appender.console.layout = org.apache.log4j.PatternLayout
    log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
    
    #文件输出的相关设置
    log4j.appender.file = org.apache.log4j.RollingFileAppender
    log4j.appender.file.File=./log/rtt.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
    
  2. 配置log4j为日志实现

    <setting name="logImpl" value="LOG4J"/>
    
  3. Log4j的使用

    image-20230422201429180


6、分页

减少数据处理量

  1. 接口

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

    <!--    分页-->
        <select id="getUserByLimit" parameterType="map" resultType="user">
            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<String, Integer>();
            map.put("startIndex",1);
            map.put("pageSize",2);
    
            List<User> userList = mapper.getUserByLimit(map);
            for (User user : userList) {
                System.out.println(user);
            }
            sqlSession.close();
        }
    

7、使用注解开发

7.1、面向接口编程

大家之前都学过面向对象编程,也学习过接口,但在真正的开发中,很多时候我们会选择面向接口编程

根本原因︰解耦,可拓展,提高复用,分层开发中,上层不用管具体的实现,大家都遵守共同的标准,使得开发变得容易,规范性更好
在一个面向对象的系统中,系统的各种功能是由许许多多的不同对象协作完成的。在这种情况下,各个对象内部是如何实现自己的,对系统设计人员来讲就不那么重要了;
而各个对象之间的协作关系则成为系统设计的关键。小到不同类之间的通信,大到各模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是指按照这种思想来编程。

关于接口的理解
接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离。-接口的本身反映了系统设计人员对系统的抽象理解。
接口应有两类:
第一类是对一个个体的抽象,它可对应为一个抽象体(abstract class);

第二类是对一个个体某一方面的抽象,即形成一个抽象面(interface) ;

一个体有可能有多个抽象面。抽象体与抽象面是有区别的。

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

7.2、使用注解开发

  1. 注解在接口上实现

    public interface UserMapper {
        @Select("select * from user")
        List<User> getUsers();
    }
    
  2. 需要在核心配置文件中绑定接口

    <mappers>
        <mapper class="com.rtt.dao.UserMapper"/>
    </mappers>
    
  3. 测试

    
    

本质:反射机制实现

底层:动态代理

7.3、CRUD

自动提交事务

public static SqlSession getSqlSession(){
    return sqlSessionFactory.openSession(true);//自动提交
}

编写接口

//方法存在多个参数,加上@param("id")注解
@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=#{uid}")
int deleteUser(@Param("uid") int id);

测试

注意:一定要将接口绑定到核心配置文件

关于@Param()注解

  • 基本类型的参数或者String类型,需要加上
  • 引用类型不用加

8、Lombok

  1. 安装lombok

  2. 导入lombok的jar包

    <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.10</version>
    </dependency>
    
  3. 在实体类上加注解即可

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    

9、多对一处理

测试环境搭建

  1. 导入lombok
  2. 新建实体类Teacher,Student
  3. 建立Mapper接口
  4. 建立Mapper.xml文件
  5. 在核心配置文件中绑定注册Mapper接口或者文件
  6. 测试

按照查询嵌套处理

 	<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="com.rtt.pojo.Teacher">
        select * from teacher where id=#{id}
    </select>

按照结果嵌套处理

<!--    按照结果嵌套处理-->
    <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="com.rtt.pojo.Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <association property="teacher" javaType="com.rtt.pojo.Teacher">
            <result property="name" column="tname"/>
        </association>
    </resultMap>

10、一对多处理

  1. 搭建环境

    实体类

    @Data
    public class Teacher {
        private int id;
        private String name;
    
        //一个老师多个学生
        private List<Student> students;
    }
    
  2. 按照结果嵌套处理

        <select id="getTeacher" resultMap="TeacherStudent">
            select s.id sid,s.name sname,t.name tname,t.id tid
            from student s,teacher t
            where s.tid=t.id and t.id=#{id}
        </select>
    
        <resultMap id="TeacherStudent" type="com.rtt.pojo.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>
    
    

11、动态SQL

动态SQL就是指根据不同的条件生成不同的SQL语句,本质还是SQL语句,只是可以在SQL层面执行逻辑代码

搭建环境

  1. 导包

  2. 编写配置文件

  3. 编写实体类

    @Data
    public class Blog {
        private int id;
        private String title;
        private String author;
        private Date createTime;
        private int views;
    }
    
  4. 编写实体类对应的Mapper文件以及Mapper.xml

IF

<select id="queryBlogIF" parameterType="map" resultType="blog ">
	select * from blog where 1=1
	<if test="title != null">
		and title = #{title}
    </if>
	<if test="author != null">
		and author = #{author}
    </if>
</select>

12、缓存

12.1简介

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

12.2MyBatis缓存

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

12.3、一级缓存

  • 一级缓存也叫本地缓存:SqlSession
    • 与数据库同一次会话期间查询到的数据会放在本地缓存中。
    • 以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库;

缓存失效情况:

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

12.4、二级缓存

  • 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
  • 基于namespace级别的缓存,一个名称空间,对应一个二级缓存;
  • 工作机制
    • 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;
    • 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;
    • 新的会话查询信息,就可以从二级缓存中获取内容;
    • 不同的mapper查出的数据会放在自己对应的缓存(map)中;

步骤:

  1. 开启全局缓存

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

  3. 测试

posted @ 2023-04-24 00:12  尧天天  阅读(43)  评论(0)    收藏  举报