• mybatis 学习


    Mybatis

    环境:

    • JDK 1.8
    • MySql 8.0
    • Maven 3.6.1
    • IDEA

    回顾:

    • JDBC
    • MySql
    • Java 基础
    • Maven
    • Junit

    框架:配置文件,最好方式看官网

    中文文档官网

    1.简介

    1.1什么是 MyBatis?

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

    1.2 持久层

    数据持久化

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

    为什么要持久化?

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

    1.3 持久层

    DAO 层,Service层,Controller 层

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

    1.4 为什么需要 Mybatis?

    • 传统 JDBC 代码太复杂,简化,框架,自动化

    • 核心作用:帮助程序猿将数据存入到数据库中

    • 作为框架不使用也行,使用更容易上手

    • 优点

      • 简单易学:
      • 灵活:mybatis不会对应用程序或者数据库的现有设计强加任何影响。 sql写在xml里,便于统一管理和优化。通过sql语句可以满足操作数据库的所有需求。
      • sql和代码的分离,提高了可维护性。解除sql与程序代码的耦合:通过提供DAO层,将业务逻辑和数据访问逻辑分离,使系统的设计更清晰,更易维护,更易单元测试。
      • 提供映射标签,支持对象与数据库的orm字段关系映射。
      • 提供对象关系映射标签,支持对象关系组建维护
      • 提供xml标签,支持编写动态sql。

      #{}和${}的区别是什么?

      • {}是预编译处理,${}是字符串替换。

      • Mybatis 在处理#{}时,会将 sql 中的#{}替换为?号,调用 PreparedStatement 的 set 方法来赋值;

      • Mybatis 在处理${}时,就是把${}替换成变量的值。

      • 使用#{}可以有效的防止 SQL 注入,提高系统安全性。

    2.第一个 Mybatis 程序

    思路:

    • 搭建环境
    • 导入 Mybatis
    • 编写代码
    • 测试

    2.1 搭建环境

    搭建数据库

    create DATABASE `mybatis`;
    use `mybatis`;
    
    CREATE TABLE `user`(
    `id` int(20) not NULL,
    `name` VARCHAR(30) default NULL,
    `pwd` VARCHAR(30) DEFAULT null,
    primary KEY(id)
    )engine=INNODB DEFAULT CHARACTER=utf8;
    
    INSERT INTO USER(`id`,`name`,`pwd`) VALUES
    (1,'zs','123456'),
    (2,'ls','123456'),
    (3,'ww','123456')
    

    导入Maven依赖

    <!--    父工程-->
    
        <dependencies>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.48</version>
            </dependency>
    
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.2</version>
            </dependency>
    
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.13</version>
                <scope>test</scope>
            </dependency>
        </dependencies>
    

    2.2 创建第一个项目

    • 编写核心配置文件
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <environments default="development">
            <environment id="development">
                <!--      事务管理-->
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.jdbc.Driver"/>
                    <!--                &amp 相当于&这里需要转义-->
                    <property name="url"
                              value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf-8"/>
                    <property name="username" value="root"/>
                    <property name="password" value="rootroot"/>
                </dataSource>
            </environment>
        </environments>
    </configuration>
    
    • 编写 mybatis 工具类
    public class MybatisUtils {
        private static SqlSessionFactory sqlSessionFactory;
    
        static {
            try {
                //使用 mybatis 第一步:获取 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编写代码

    • 实体类

    • Mapper 接口

    public interface UserMapper {
        List<User> getUserList();
    }
    
    • 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 接口-->
    <mapper namespace="com.study.mapper.UserMapper">
    
      <select id="getUserList" resultType="com.study.pojo.User">
       select * from user ;
      </select>
      
    </mapper>
    

    2.4测试

    注意点

    org.apache.ibatis.binding.BindingException: Type interface com.study.mapper.UserMapper is not known to the MapperRegistry.

    MapperRegistry是什么?

    核心配置文件注册,需要注册 mapper 的查询语句,在 mybatis-config.xml 中

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

    java.lang.ExceptionInInitializerError,由于 mapper.xml 文件在 java 下,maven 导出的资源默认是 resource,需要配置 java 下的文件导出

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

    最终测试

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

    3.CRUD

    1.namepace

    namepace 中包名要和 mapper 接口包名一致!

    2.select

    选择,查询语句

    • id 就是对应 namespace 中的方法名
    • resultType SQL 语句执行的返回值
    • parameterType 参数类型

    3.insert

    • 编写接口
    • 编写 mapper.xml 对应方法的语句
    • 测试

    4.update

    5.delete

    注意点:

    (增删改一定要进行事务提交)

    接口

    public interface UserMapper {
        //查询所有用户信息
        List<User> getUserList();
    
        //根据 id 查询用户
        User getUserById(int id);
    
        //增加用户
        int addUser(User user);
    
        //修改用户
        int updateUser(User user);
    
        //删除用户
        int deleteUserById
    

    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 接口-->
    <mapper namespace="com.study.mapper.UserMapper">
        <select id="getUserList" resultType="com.study.pojo.User">
    
    
       select * from user ;
    
    
        </select>
    
        <select id="getUserById" resultType="com.study.pojo.User" parameterType="int">
    
    
      select * from user where id = #{id}
    
    
        </select>
    
        <!--   values 对象中属性可以直接取出来,与 pojo 类的成员变量名字保持一致-->
        <insert id="addUser" parameterType="com.study.pojo.User">
    
        insert into user(id,name,pwd)values (#{id},#{name},#{pwd})
    
        </insert>
    
        <update id="updateUser" parameterType="com.study.pojo.User" >
        update user set name =#{name},pwd=#{pwd} where id =#{id};
        </update>
    
        <delete id="deleteUserById" parameterType="int">
        delete from user where id =#{id}
    </delete>
    </mapper>
    

    测试

    public class UserDaoTest {
    
        @Test
        public void test() {
            //h 获取 sqlSession对象
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            //方式一
            try {
                sqlSession = MybatisUtils.getSqlSession();
                UserMapper mapper = sqlSession.getMapper(UserMapper.class);
                List<User> userList = mapper.getUserList();
                for (User user : userList) {
                    System.out.println(user);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //关闭 sqlSession
                sqlSession.close();
            }
    
        }
    
        @Test
        public void getUserById() {
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            User user = mapper.getUserById(1);
            System.out.println(user);
        }
    
        //增删改查需要事务提交
        @Test
        public void addUser() {
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            int i = mapper.addUser(new User(6, "赵六", "123456"));
            if (i>0){
                System.out.println("插入成功");
            }
            //提交事务
            sqlSession.commit();
            sqlSession.close();
        }
    
        @Test
        public void update(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            int i = mapper.updateUser(new User(6, "大气", "123123"));
            if (i>0){
                System.out.println("修改成功");
            }
            //提交事务
            sqlSession.commit();
            sqlSession.close();
        }
    
        @Test
        public  void deleteUserById(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            int i = mapper.deleteUserById(6);
            sqlSession.commit();
            sqlSession.close();
        }
    }
    

    对象传递参数,直接 sql 中取对的属性即可

    <!--   values 对象中属性可以直接取出来,与 pojo 类的成员变量名字保持一致-->
        <insert id="addUser" parameterType="com.study.pojo.User">
        insert into user(id,name,pwd)values (#{id},#{name},#{pwd})
        </insert>
    

    只有一个基本数据类型的属性下,可以直接在基本数据类型取

    <delete id="deleteUserById" parameterType="int">
        delete from user where id =#{id}
    </delete>
    

    6.万能 map

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

    Map传递参数,直接在 sql 中取出 key 即可

    <!--    对象中的属性,可以直接取出来传递 map 中的 key-->
         <insert id="addUser2" parameterType="map"> 参数类型
        insert into user(id,name,pwd)values (#{userid},#{username},#{password})
        </insert>
    

    使用 map 的话传递参数就是 key,来取值,多个参数用 map 或注解(对应上面的 addUser2)

     @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", 5);
            map.put("password", 5);
            mapper.addUser2(map);
        }
    

    7.模糊查询

    怎么查?

    1. java 代码执行时候,传递通配符
    //模糊查询
        List<User> getUserLike(String value);
    
    <!--    模糊查询-->
    <select id="getUserLike" resultType="com.study.pojo.User">
    select * from user where name like #{value}
    </select>
    
     @Test
        public  void getUserLike(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            List<User> list = mapper.getUserLike("%l%");
            for (User user : list) {
                System.out.println(user);
            }
        }
    
    1. 在 sql 拼接中使用通配符
    <!--    模糊查询-->
    <select id="getUserLike" resultType="com.study.pojo.User">
    select * from user where name like "%"#{value}"%"
    </select>
    

    4.配置解析

    1.核心配置文件

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

    2.环境变量(environments)

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

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

    事务管理器(transactionManager)

    在 MyBatis 中有两种类型的事务管理器(也就是 type="[JDBC|MANAGED]")默认事务管理器 JDBC

    数据源(dataSource)

    dataSource 元素使用标准的 JDBC 数据源接口来配置 JDBC 连接对象的资源。

    有三种内建的数据源类型(也就是 type="[UNPOOLED|POOLED|JNDI]"):默认是 POOLED,让响应更快一些

    3.属性(properties)

    我们可以使用properties 属性实现引用配置文件

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

    • 注意
    properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,reflectorFactory?,plugins?,environments?,databaseIdProvider?,mappers?)"
    

    xml 进行配置需要按照上述的顺序进行否则报错!!!

    编写配置文件(db.properties)

    driver= com.mysql.jdbc.Driver
    url= jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true
    username= root
    password= rootroot
    

    引入配置文件

    <!--    引入外部配置文件-->
        <properties resource="db.properties">
            <property name="username" value="root"/>
            <property name="password" value="11111"/>
        </properties>
    
    • 可以直接引入外部文件
    • 可以再其中增加一些属性配置
    • 如果两个文件存在同一个字段,优先使用外部配置(db.properties)文件

    4.类型别名(typeAliases)

    类型别名可为 Java 类型设置一个缩写名字。 它仅用于 XML 配置,意在降低冗余的全限定类名书写。

    <!-- 方式一   给实体类起别名-->
        <typeAliases>
            <typeAlias type="com.study.pojo.User" alias="User"/>
        </typeAliases>
    
    <!--方式二 包起别名 在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名
    使用注解则在实体类上面加@Alias 上加自己的缩写名字如:@Alias("user")-->
     <typeAliases>
           <package name="com.study.pojo"/>
        </typeAliases>
    
    
    • 实体类少使用第一种,多建议使用第二种

    5.设置(settings)

    image-20210124234149141

    image-20210124234056020

    image-20210124234120368

    6.映射器(mappers)

    注册绑定我们的 mapper 文件

    方式一【推荐使用】

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

    方式二:使用 class 文件绑定

     <mappers>
            <mapper class="com.study.mapper.UserMapper"></mapper>
    </mappers>
    
    • 接口和配置文件必须同名
    • 接口和配置文件必须在同一个包下

    方式三:通过 package

        <mappers>
            <package name="com.study.mapper"/>
        </mappers>
    
    • 接口和配置文件必须同名
    • 接口和配置文件必须在同一个包下

    5.作用域和生命周期

    SqlSessionFactoryBuilder

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

    SqlSessionFactory

    • 一旦创建就一直存在,没有任何理由丢弃它或重新创建另一个,类似连接池
    • 应用作用域(程序开始到程序结束)
    • 最简单就是使用单例模式或静态单例模式

    SqlSession

    • 连接连接池的一个请求
    • 每个线程都应该有它自己的 SqlSession 实例。SqlSession 的实例不是线程安全的,因此是不能被共享的。
    • 最佳作用域方法中,用完需赶紧关闭,否则资源占用 SqlSession.close()

    依赖注入框架可以创建线程安全的、基于事务的 SqlSession 和映射器,并将它们直接注入到你的 bean 中,因此可以直接忽略它们的生命周期

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

    测试

    
    
        <select id="getUserById" resultType="user" parameterType="int">
      select * from user where id = #{id}
    <!--  类型处理器,回去寻找 pwd 对应的属性名,但是找不到属性名里是 password-->
    <!--select id,name,pwd from user where id = #{id}-->
        </select>
    

    解决方法:

    • 起别名
        <select id="getUserById" resultType="user" parameterType="int">
    select id,name,pwd as password from user where id = #{id}
        </select>
    

    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 id,name,pwd  from user where id = #{id}
    </select>
    
    • resultMap 元素是 Mybatis 中最重要最强大的元素
    • ResultMap 设计思路是,对于简单语句根本不需要配置显式的结果集映射,而复杂一点的语句只需要描述他们的关系就行

    7.日志

    7.1 日志工厂

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

    image-20210124234120368

    SLF4J

    LOG4J 【掌握】

    LOG4J2

    JDK_LOGGING

    COMMONS_LOGGING

    STDOUT_LOGGING 【掌握】

    NO_LOGGING

    在 Mybaits 具体使用哪个日志实现,在核心配置文件中设置

    STDOUT_LOGGING标准输出

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

    image-20210125111736348

    7.2 LOG4J

    什么是 log4j?

    • Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件
    • 我们也可以控制每一条日志的输出格式
    • 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。
    • 最令人感兴趣的就是,这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码
    1. 先导入 log4j 的包
    <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
    </dependency>
    
    1. log4j.properties
    log4j.rootLogger=debug,console,logfile
    
    ### appender.console控制台相关设置 ###
    log4j.appender.console=org.apache.log4j.ConsoleAppender
    log4j.appender.console.layout=org.apache.log4j.PatternLayout
    log4j.appender.console.layout.ConversionPattern=<%d> %5p (%F:%L) [%t] (%c) - %m%n
    log4j.appender.console.Target=System.out
    
    ### appender.logfile文件输出相关配置 ###
    log4j.appender.logfile=org.apache.log4j.RollingFileAppender
    log4j.appender.logfile.File=./log/study.log
    log4j.appender.logfile.MaxFileSize=500KB
    log4j.appender.logfile.MaxBackupIndex=7
    log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
    log4j.appender.logfile.layout.ConversionPattern=<%d> %p (%F:%L) [%t] %c - %m%n
    
    1. 配置 log4j (核心配置文件中,注意 settings 在文件中的顺序)
     <settings>
            <setting name="logImpl" value="LOG4J"/>
    </settings>
    
    1. 测试运行

    简单使用

    1. 在使用 log4j 的类中,导入包 import org.apache.log4j.Logger;

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

    static  Logger logger = Logger.getLogger(Logi4jTest.class);
    
     @Test
        public void Test() {
        logger.info("info:进入了 testLog4j");
        logger.debug("debug:进入了 testLog4j");
        logger.error("error:进入了 testLog4j");
    
        }
    
    1. 常用日志级别
    logger.info("info:进入了 testLog4j");
    logger.debug("debug:进入了 testLog4j");
    logger.error("error:进入了 testLog4j");
    

    8. 分页

    为什么分页?

    • 减少数据处理量

    使用 limit 分页

    语法:select * from user limit startIndex ,pageSize
    select * from user limit 3; #[0,n-1]索引下标从 0 开始
    

    使用 Mybatis 分页,核心是 Sql

    1. 接口
    //分页
    List<User>  getUserByLimit(Map<String ,Integer> map);
    
    1. Mapper.xml
    <resultMap id="UserMap1" type="user">
    <result column="pwd" property="password"></result>
    </resultMap>
    
    <select id="getUserByLimit" parameterType="map" resultMap="UserMap1">
    select * from user limit #{startIndex},#{pageSize}
    </select>
    
    1. 测试
    @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> userByLimit = mapper.getUserByLimit(map);
        for (User user : userByLimit) {
            System.out.println(user);
        }
        sqlSession.close();
    }
    

    pageHelper 简单使用

    导入依赖

    <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper</artifactId>
                <version>5.1.11</version>
    </dependency>
    

    配置文件

    <!--helperDialect:分页插件会自动检测当前的数据库链接,自动选择合适的分页方式。 你可以配置helperDialect属性来指定分页插件使用哪种方言。配置时,可以使用下面的缩写值:配置数据库-->
    <!--    分页插件-->
        <plugins>
            <!-- com.github.pagehelper为PageHelper类所在包名 -->
            <plugin interceptor="com.github.pagehelper.PageInterceptor">
                <!-- 配置数据库 -->
                <property name="helperDialect" value="mysql"/>
            </plugin>
        </plugins>
    

    编写测试类

    一些 API

    • PageHelper.startPage(int pageNum,int pageSize);
      给定分页参数,该方法需要在执行查询之前调用 pageNum:起始的页数,从 1 开始计算。 pageSize:每页显示的条数。
    • PageInfo 对象 存放分页结果对象
    • pageInfo.getList() 获取分页查询结果。
    • pageInfo.getTotal() 获取查询总条数。
    • pageInfo.getPages() 获取总页数。
    • pageInfo.getPageNum() 获取当前页。
    • pageInfo.getSize() 获取每页显示的条数。
      @Test
        public void getUserByBounds(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            PageHelper.startPage(2, 2);//第几页,每页显示几条
            List<User> users = mapper.getUserByBounds();
            PageInfo<User> info = new PageInfo<>(users);//将查询结果集进行分页
            List<User> list = info.getList();//遍历分页后的结果集
            for (User user : list) {
                System.out.println(user);
            }
          	System.out.println("共有几页"+info.getPages());//2
            System.out.println("每页几条"+info.getPageSize());//2
            System.out.println("共多少条"+info.getTotal());//4
    

    9.使用注解开发

    9.1 面向接口编程

    根本原因:解耦

    关于接口理解

    • 定义接口与实现的分离

    • 接口是对系统抽象的理解

    • 接口应有两类

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

      一个体可能有多个抽象面,抽象体和抽象面是有区别的

    三个面向区别

    面向对象是指:我们考虑问题,以对象为单位,考虑他的属性和方法

    面向过程是指,一个具体流程怎么实现

    接口设计和非接口设计是针对复用技术而言,与面向对象(过程)不是一个问题,更多体现是对系统整体的架构

    9.2 使用注解开发

    1. 注解直接在接口上实现
    public interface UserMapper {
    
        @Select("select * from user")
        List<User> getUsers();
      
      
      //方法存在多个参数所有参数必须加上@Param注解id 和#{}的一致
        @Select("select * from USER where id=#{id2} ")
        User getUserById(@Param("id2") int id);
    
    }
    
    1. 在核心配置文件中绑定
    <!--    使用注解,绑定接口-->
        <mappers>
            <mapper class="com.study.mapper.UserMapper"/>
        </mappers>
    

    本质:反射机制实现

    底层:动态代理

    9.3注解 CRUD

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

    public static SqlSession getSqlSession() {
            return sqlSessionFactory.openSession(true);//true 则自动提交事务
        }
    
    //增删改
        //#{}里面是实体类属性,前面的是返回值是数据库字段属性
        @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 update(User user);
    
        @Delete("delete from user where id=#{uid}")
        int delete(@Param("uid") int id);
    

    关于@param

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

    #{} 和${}

    (会出现 sql 注入:没有对 sql 语句做判断)

    1. #{}是预编译处理,${}是字符串替换。mybatis在处理#{}时,会将sql中的#{}替换为?号,先进行预编译再调用PreparedStatement的set方法来赋值;mybatis在处理 ${ } 时,就是把 ${ } 替换成变量的值。使用 #{} 可以有效的防止SQL注入,提高系统安全性。

    2. 对于这个题目我感觉要抓住两点:

      • (1) ${ } 仅仅为一个纯碎的 String 替换,在 Mybatis 的动态 SQL 解析阶段将会进行变量替换。

      • (2)预编译的机制。预编译是提前对SQL语句进行预编译,而其后注入的参数将不会再进行SQL编译。我们知道,SQL注入是发生在编译的过程中,因为恶意注入了某些特殊字符,最后被编译成了恶意的执行操作。而预编译机制则可以很好的防止SQL注入。而${}则不会进行预编译,直接进行 DBMS,直接进入数据库

    Mybatis 详细执行流程

    image-20210125151102128

    10.Lombok

    使用步骤:

    • 下载插件
    • 导包
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.16</version>
            </dependency>
    
    • 在类上加注解尤其在 pojo 类

    image-20210125164523859

    image-20210125164626355

    缺点:

    • 不支持多参数构造器重载,可自己手动加
    • 代码可读性降低

    真实开发中根据实际情况而定。

    11.多对一(相对)

    • 多个学生关联一个老师
    • 对于老师而言,集合,一个老师有很多学生
    #老师表
    CREATE TABLE `teacher` (
      `id` int NOT NULL,
      `name` varchar(30) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    
    # 学生表
    CREATE TABLE `student` (
      `id` int NOT NULL,
      `name` varchar(30) DEFAULT NULL,
      `tid` int DEFAULT NULL,
      PRIMARY KEY (`id`),
      KEY `fktid` (`tid`),
      CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    

    测试环境

    1. 导包
    2. 新建实体类 Teacher,Student
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class Student {
        private int id;
        private String name;
        //学生需要关联一个老师
        private Teacher teacher;
    }
    
    
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class Teacher {
        private int id;
        private String name;
    }
    

    3.建立 Mapper接口

    public interface StudentMapper {
        //查询所有的学生信息以及对应老师的信息
        List<Student> getStudent();
    
        List<Student> getStudent2();
    }
    
    public interface TeacherMapper {
    
        @Select("select * from teacher where id =#{id}")
        Teacher getTeacher(@Param("id") int id);
    }
    

    4.在核心配置文件中绑定 Mapper 接口或文件

     <mappers>
            <mapper resource="com/study/mapper/StudentMapper.xml"></mapper>
            <mapper resource="com/study/mapper/TeacherMapper.xml"></mapper>
        </mappers>
    

    5.测试

    按照查询嵌套处理

    <!--
    思路:
    select s.id,s.name,t.id ,t.name from student s ,teacher t where tid =(select id from teacher);
         1.查询所有学生信息
         2.根据查询出来的学生 tid,寻找对应老师-->
    <select id="getStudent" resultMap="StudentTeacher">
    select * from student;
    </select>
    
    <resultMap id="StudentTeacher" type="student">
    <result column="id" property="id"/>
    <result column="name" property="name"/>
    
    <!--赋值的属性,我们需要单独出来,对象:association 集合:collection-->
    <association property="teacher" column="tid" javaType="teacher" select="teacher"/>
    </resultMap>
    
    <select id="teacher" resultType="teacher">
    select * from teacher where id =#{tid};	//#里随意写都能找到
    </select>
    

    按照结果嵌套处理

    <!--按照结果嵌套出来
    思路:
         1.查询所有学生信息
         2.根据查询出来的学生 tid,寻找对应老师
    -->
    <select id="getStudent2" resultMap="StudentTeacher2">
    select s.id sid,s.name sname,t.id tid,t.name tname
    from student s,teacher t
    where s.tid ;
    </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"/>
    <result property="id" column="tid"/>
    </association>
    </resultMap>
    

    12.一对多

    比如:一个老师对应多个学生

    实体类

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class Teacher {
        private int id;
        private String name;
        //一个老师拥有多个学生
        private List<Student> students;
    }
    

    接口

    public interface TeacherMapper {
    
        //获取老师
        Teacher getTeacher(@Param("tid") int id);
    
    }
    

    mapper.xml

    按结果嵌套查询(推荐)

    <!--按结果嵌套查询-->
    <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 =#{tid};
    </select>
    
    <resultMap id="TeacherStudent" type="teacher">
    <result property="id" column="tid"/>
    <result property="name" column="tname"/>
    
    <!--复杂的属性,我们需要单独出来,对象使用 association 集合:collection
    javaType=""指定属性类型
    集合中的泛型,使用 offType 获取
    -->
    <collection property="students" ofType="student">
    <result property="id" column="sid"/>
    <result property="name" column="sname"/>
    <result property="tid" column="tid"/>
    </collection>
    
    </resultMap>
    

    按查询嵌套处理

    <select id="getTeacher2" resultMap="TeacherStudent2">
    select * from teacher where id =#{tid}
    </select>
    
    <resultMap id="TeacherStudent2" type="teacher">
    <!--<result property="id" column="id"/> 和*里面查询的结果集一样省略-->
    <!--<result property="name" column="name"/>-->
    <!--这里需要的是 list-->
    <collection property="students" javaType="arraylist" ofType="student" select="getStudentByTeacherId" column="id"/>
    </resultMap>
    
    <select id="getStudentByTeacherId" resultType="student">
    select * from student where tid =#{tid}
    </select>
    
    • 测试
     @Test
        public void getTeacher(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
            Teacher teacher = mapper.getTeacher(1);
                System.out.println(teacher);
                sqlSession.close();
        }
    

    面试必问

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

    13. 动态 SQL

    什么是动态 SQL?动态SQL 就是只根据不同的条件生成不同的 SQL 语句

    搭建环境

    CREATE TABLE `blog` (
    `id` VARCHAR(50) not NULL COMMENT '博客 id',
    `NAME` VARCHAR(100) DEFAULT NULL COMMENT '博客标题',
    `title` VARCHAR(30) DEFAULT NULL COMMENT '博客作者',
    `author` VARCHAR(30) DEFAULT NULL COMMENT '博客作者',
    `create_time` datetime not null COMMENT '创建时间',
    `views` INT(30) not NULL COMMENT '浏览量'
    ) ENGINE = INNODB DEFAULT charset=utf8
    

    创建一个基础工程

    1. 导包
    2. 编写核心配置文件
    <!--        开启驼峰命名转换,数据库是 create_time,实体类里写了 createTime,这样就可以自己映射过来-->
            <setting name="mapUnderscoreToCamelCase" value="true"/>
    
    1. 编写实体类对应的 Mapper 接口和 Mapper.xml
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Blog {
        private String id;
        private String title;
        private String author;
        private Date createTime;//属性名和字段名不一致
        private int views;
    
    }
    
    public interface UserMapper {
        User queryUserById(@Param("pid") int id);
    }
    
    <select id="queryUserById" resultType="user">
    select * from user where id =#{pid}
    </select>
    

    if

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

     <select id="queryBlogIf" parameterType="map" resultType="blog">
    
            select * from blog
    <!-- where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。-->
            <where>
    
            <if test="title != null">
    
            and title =#{title}
    
            </if>
            <if test="author != null">
    
            and author = #{author}
            </if>
            </where>
        </select>
    

    choose、when、otherwise

    MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。只会满足一个条件要么是 when 要么是 otherwise

        <select id="queryBlogChoose" parameterType="map" resultType="blog">
            
        select * from blog
        
            <where>
                <choose>
                    <when test="title != null">
                        title=#{title}
                    </when>
    
                    <when test="author != null">
                        
             				and   author=#{author}
            
                    </when>
    
                    <otherwise>
                        
            			and views =#{views}
                    </otherwise>
                </choose>
            </where>
        </select>
    

    set

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

     <!--update bolg set title=?,author=? where id =?-->
    <update id="updateBlog" parameterType="map" >
        update blog
        <set>
        <if test="title!=null">
        title=#{title},
        </if>
        <if test="author!=null">
        author=#{author}
        </if>
        </set>
         where id =#{id}
        </update>
    

    所谓动态 sql 还是 sql 语句,只是我们可以再 sql 层面去执行一些逻辑代码(if where set choose)就判断条件是否成了的

    SQL 片段

    有些时候我们可以把通用的代码抽取出来,进行复用

    1. 使用 sql 标签抽取公共部分
    <sql id="if-title">
      <if test="title != null">
                    and title =#{title}
                </if>
                <if test="author != null">
                 and author = #{author}
                </if>
    </sql>
    
    1. 在需要使用的地方使用 include 标签引用
     <select id="queryBlogIf" parameterType="map" resultType="blog">
            select * from blog
            <where>
              <include refid="if-title"></include>
            </where>
        </select>
    

    注意事项

    • 最好基于单表定义 SQL 片段
    • 不要在 sql 标签中出现 where 标签

    foreach

     <!--现在传递一个 map,map 中可以存在一个集合
        select * from blog where 1=1 and (id=1 or id =2 or id =3);
    		SELECT * from blog where id in (1,2,3)
        separator 分割符
        open="and (" and 后一定要有空格否则报错
        -->
        <select id="queryBlogForeach" parameterType="map" resultType="blog">
         <!-- 	select * from blog id in
        	<foreach collection="ids" item="id" open="and (" close=")" separator=",">
                        #{id}
                    </foreach>	-->
    
            select * from blog
                <where>
                    <foreach collection="ids" item="id" open="and (" close=")" separator="or">
                        id =#{id}
                    </foreach>
                </where>
        </select>
    

    动态 SQL 就是在拼接 sql 语句,我们只要保证 sql 正确性,按照 sql 的正确性进行排列组合就可以了。拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号

    使用时,先将 SQL语句列出,再写动态 SQL

    14.缓存

    14.1 简介

    查询:连接数据库,耗资源!
    一次查询的结果,给暂存在一个可以直接取到的地方!一般放内存里,这些数据就叫缓存
    	
    我们再次查询相同数据的时候,直接走缓存,就不用走数据库了
    

    1.1什么是缓存?

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

    1.2 为什么使用缓存?

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

    1.3什么样的数据能使用缓存?

    • 经常查询而不经常改变的数据

    14.2Mybatis 缓存

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

    14.3 一级缓存

    • 以及缓存也叫本地缓存
      • 与数据库同一次会话期间查询到的数据会放入本地缓存
      • 以后如果需要获取相同数据直接在缓存取

    测试;

    1. 开启日志(核心配置文件)
    <settings>
            <setting name="logImpl" value="STDOUT_LOGGING"/>
    <!--        开启驼峰命名转换,数据库是 create_time,实体类里写了 createTime,这样就可以自己映射过来-->
            <setting name="mapUnderscoreToCamelCase" value="true"/>
        </settings>
        <!--    <settings>-->
        <!--        <setting name="logImpl" value="LOG4J"/>-->
        <!--    </settings>-->
    
    1. 测试一个 SqlSession 中查询两次相同记录
      @Test
        public void queryUserById(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            User user1 = mapper.queryUserById(1);
            System.out.println(user1);
            System.out.println("____________");
            User user2 = mapper.queryUserById(1);
            System.out.println(user2);
            System.out.println(user1.equals(user2));
            sqlSession.close();
        }
    
    1. 查看日志输出

    image-20210126233658927

    缓存失效情况

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

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

    14.4 二级缓存

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

    步骤:

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

    2.在使用二级缓存的 Mapper 项目中开启

    <!--在当前 mapper.xml 使用二级缓冲-->
    <cache/>
    

    也可以自定义参数

    <cache
      eviction="FIFO"
      flushInterval="60000"
      size="512"
      readOnly="true"/>
    

    3.测试

    问题:我们没有自定义参数时会报错,因此实体类要进行序列化

    小结:

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

    14.5 缓存原理

    image-20210127094030857

    悲观者正确,乐观者成功
  • 相关阅读:
    控件属性大全(持续更新)
    STM32F0使用LL库实现UART接收
    STM32F0 LL库IIC第二地址配置错误
    C# 抽象类小谈
    DevExpress 动态换肤
    DevExpress ChartControl大数据加载时有哪些性能优化方法
    Devexpress WPF ChartControl 多Y轴
    Lambda表达式的使用
    Prism--MVVM 之Command
    WPF Toolkit Chart--动态换列
  • 原文地址:https://www.cnblogs.com/freebule/p/14462566.html
Copyright © 2020-2023  润新知