zoukankan      html  css  js  c++  java
  • 再谈 MyBatis 复杂查询

    一对一查询


    在实际开发中,经常会遇到一对一查询,一对多查询等。这里我们先来看一对一查询。例如:每本书都有一个作者,作者都有自己的属性,根据这个,我来定义两个实体类:

    public class Book {
        
        private Integer id;
        private String name;
        private Author author;
    	
        // 省略 getter/setter
    }
    
    public class Author {
        
        private Integer id;
        private String name;
        private Integer age;
    
       // 省略 getter/setter
    }
    

    然后,在数据库中,添加两张表:

    CREATE DATABASE /*!32312 IF NOT EXISTS*/`test01` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci */ /*!80016 DEFAULT ENCRYPTION='N' */;
    
    USE `test01`;
    
    /*Table structure for table `author` */
    
    DROP TABLE IF EXISTS `author`;
    
    CREATE TABLE `author` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `name` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL,
      `age` int(11) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
    
    /*Data for the table `author` */
    
    /*Table structure for table `book` */
    
    DROP TABLE IF EXISTS `book`;
    
    CREATE TABLE `book` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `name` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL,
      `aid` int(11) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
    

    添加成功后,我们新建一个 BookMapper,BookMapper 中定义了一个查询 Book 的方法,但是我希望查出来 Book 的同时,也能查出来它的 Author:

    public interface BookMapper {
        
        Book getBookById(Integer id);
    }
    

    再定义一个 BookMapper.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="com.antonio.hello.mybatis.mapper.BookMapper">
    
        <resultMap id="BookWithAuthor" type="com.antonio.hello.mybatis.entity.Book">
            <id column="id" property="id"/>
            <result column="name" property="name"/>
            <association property="author" javaType="com.antonio.hello.mybatis.entity.Author">
                <id column="aid" property="id"/>
                <result column="aname" property="name"/>
                <result column="aage" property="age"/>
            </association>
        </resultMap>
    
        <select id="getBookById" resultMap="BookWithAuthor">
            SELECT b.*,a.`age` AS aage,a.`id` AS aid,a.`name` AS aname FROM book b,author a WHERE b.`aid`=a.`id` AND b.`id`=#{id}
        </select>
    </mapper>
    

    在这个查询 SQL 中,首先应该做好一对一查询,然后,返回值一定要定义成 resultMap,注意,这里千万不能写错。然后,在 resultMap 中,来定义查询结果的映射关系。其中,association 节点用来描述一对一的关系。这个节点中的内容,和 resultMap 一样,也是 id,result 等,在这个节点中,我们还可以继续描述一对一。

    由于在实际项目中,每次返回的数据类型可能都会有差异,这就需要定义多个 resultMap,而这多个 resultMap 中,又有一部份属性是相同的,所以,我们可以将相同的部分抽出来,做成一个公共的模板,然后被其他 resultMap 继承,优化之后的 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">
    <mapper namespace="com.antonio.hello.mybatis.mapper.BookMapper">
    
        <resultMap id="BaseResultMap" type="com.antonio.hello.mybatis.entity.Book">
            <id column="id" property="id"/>
            <result column="name" property="name"/>
        </resultMap>
        
        <resultMap id="BookWithAuthor" type="com.antonio.hello.mybatis.entity.Book" extends="BaseResultMap">
            <association property="author" javaType="ocom.antonio.hello.mybatis.entity.Author">
                <id column="aid" property="id"/>
                <result column="aname" property="name"/>
                <result column="aage" property="age"/>
            </association>
        </resultMap>
    
        <select id="getBookById" resultMap="BookWithAuthor">
            SELECT b.*,a.`age` AS aage,a.`id` AS aid,a.`name` AS aname FROM book b,author a WHERE b.`aid`=a.`id` AND b.`id`=#{id}
        </select>
    </mapper>
    

    懒加载

    上面这种加载方式,是一次性的读取到所有数据。然后在 resultMap 中做映射。如果一对一的属性使用不是很频繁,可能偶尔用一下,这种情况下,我们也可以启用懒加载。

    懒加载:就是先查询 book,查询 book 的过程中,不去查询 author,当用户第一次调用了 book 中的 author 属性后,再去查询 author。例如,我们再来定义一个 Book 的查询方法:

    Book getBookById2(Integer id);
    
    Author getAuthorById(Integer id);
    

    接下来,在 mapper 中定义相应的 SQL:

    <resultMap id="BaseResultMap" type="com.antonio.hello.mybatis.entity.Book">
        <id column="id" property="id"/>
        <result column="name" property="name"/>
    </resultMap>
    
    <resultMap id="BookWithAuthor2" type="com.antonio.hello.mybatis.entity.Book" extends="BaseResultMap">
        <association property="author" javaType="com.antonio.hello.mybatis.entity.Author"
                     select="com.antonio.hello.mybatis.mapper.BookMapper.getAuthorById" column="aid" fetchType="lazy"/>
    </resultMap>
    
    <select id="getBookById2" resultMap="BookWithAuthor2">
        select * from book where id=#{id};
    </select>
    
    <select id="getAuthorById" resultType="com.antonio.hello.mybatis.entity.Author">
        select * from author where id=#{aid};
    </select>
    

    这里,定义 association 的时候,不直接指定映射的字段,而是指定要执行的方法,通过 select 字段来指定,column 表示执行方法时传递的参数字段,最后的 fetchType 表示开启懒加载。当然,要使用懒加载,还需在全局配置中开启:

    <settings>
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>
    

    一对多查询


    一对多查询,也是一个非常典型的使用场景。比如用户和角色的关系,一个用户可以具备多个角色。首先我们准备三个表:

    SET FOREIGN_KEY_CHECKS=0;
    
    -- ----------------------------
    -- Table structure for role
    -- ----------------------------
    DROP TABLE IF EXISTS `role`;
    CREATE TABLE `role` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `name` varchar(32) DEFAULT NULL,
      `nameZh` varchar(32) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
    
    -- ----------------------------
    -- Records of role
    -- ----------------------------
    INSERT INTO `role` VALUES ('1', 'dba', '数据库管理员');
    INSERT INTO `role` VALUES ('2', 'admin', '系统管理员');
    INSERT INTO `role` VALUES ('3', 'user', '用户');
    
    -- ----------------------------
    -- Table structure for user
    -- ----------------------------
    DROP TABLE IF EXISTS `user`;
    CREATE TABLE `user` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `username` varchar(32) DEFAULT NULL,
      `password` varchar(255) DEFAULT NULL,
      `enabled` tinyint(1) DEFAULT NULL,
      `locked` tinyint(1) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
    
    -- ----------------------------
    -- Records of user
    -- ----------------------------
    INSERT INTO `user` VALUES ('1', 'root', '$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq', '1', '0');
    INSERT INTO `user` VALUES ('2', 'admin', '$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq', '1', '0');
    INSERT INTO `user` VALUES ('3', 'sang', '$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq', '1', '0');
    
    -- ----------------------------
    -- Table structure for user_role
    -- ----------------------------
    DROP TABLE IF EXISTS `user_role`;
    CREATE TABLE `user_role` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `uid` int(11) DEFAULT NULL,
      `rid` int(11) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
    
    -- ----------------------------
    -- Records of user_role
    -- ----------------------------
    INSERT INTO `user_role` VALUES ('1', '1', '1');
    INSERT INTO `user_role` VALUES ('2', '1', '2');
    INSERT INTO `user_role` VALUES ('3', '2', '2');
    INSERT INTO `user_role` VALUES ('4', '3', '3');
    SET FOREIGN_KEY_CHECKS=1;
    

    这三个表中,有用户表,角色表以及用户角色关联表,其中用户角色关联表用来描述用户和角色之间的关系,他们是一对多的关系。然后,根据这三个表,创建两个实体类:

    public class User {
        private Integer id;
        private String username;
        private String password;
        private List<Role> roles;
    	
        // 省略 setter/getter
    }
    
    public class Role {
        private Integer id;
        private String name;
        private String nameZh;
    		
        // 省略 setter/getter
    }
    

    接下来,定义一个根据 id 查询用户的方法:

    User getUserById(Integer id);
    

    然后,定义该方法的实现:

    <resultMap id="UserWithRole" type="com.antonio.hello.mybatis.entity.User">
        <id column="id" property="id"/>
        <result column="username" property="username"/>
        <result column="password" property="password"/>
        <collection property="roles" ofType="com.antonio.hello.mybatis.entity.Role">
            <id property="id" column="rid"/>
            <result property="name" column="rname"/>
            <result property="nameZh" column="rnameZH"/>
        </collection>
    </resultMap>
    
    <select id="getUserById" resultMap="UserWithRole">
        SELECT u.*,r.`id` AS rid,r.`name` AS rname,r.`nameZh` AS rnameZh FROM USER u,role r,user_role ur WHERE u.`id`=ur.`uid` AND ur.`rid`=r.`id` AND u.`id`=#{id}
    </select>
    

    在 resultMap 中,通过 collection 节点来描述集合的映射关系。在映射时,会自动将一的一方数据集合并,然后将多的一方放到集合中,能实现这一点,靠的就是 id 属性。当然,这个一对多,也可以做成懒加载的形式,那我们首先提供一个角色查询的方法:

    List<Role> getRolesByUid(Integer id);
    

    然后,在 XML 文件中,处理懒加载:

    <resultMap id="UserWithRole" type="com.antonio.hello.mybatis.entity.User">
        <id column="id" property="id"/>
        <result column="username" property="username"/>
        <result column="password" property="password"/>
        <collection property="roles" select="com.antonio.hello.mybatis.mapper.UserMapper.getRolesByUid" column="id" fetchType="lazy">
        </collection>
    </resultMap>
    
    <select id="getUserById" resultMap="UserWithRole">
        select * from user  where id=#{id};
    </select>
    
    <select id="getRolesByUid" resultType="com.antonio.hello.mybatis.entity.Role">
        SELECT r.* FROM role r,user_role ur WHERE r.`id`=ur.`rid` AND ur.`uid`=#{id}
    </select>
    

    定义完成之后,我们的查询操作就实现了懒加载功能。

    查询缓存


    MyBatis 一级缓存

    Mybatis 一级缓存的作用域是同一个 SqlSession,在同一个 sqlSession 中两次执行相同的 sql 语句,第一次执行完毕会将数据库中查询的数据写到缓存(内存),第二次会从缓存中获取数据将不再从数据库查询,从而提高查询效率。当一个 sqlSession 结束后该 sqlSession 中的一级缓存也就不存在了。Mybatis 默认开启一级缓存。

    public class Main2 {
        public static void main(String[] args) {
            SqlSessionFactory instance = SqlSessionFactoryUtils.getInstance();
            SqlSession sqlSession = instance.openSession();
            BookMapper mapper = sqlSession.getMapper(BookMapper.class);
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            User user = userMapper.getUserById(1);
            user = userMapper.getUserById(1);
            user = userMapper.getUserById(1);
            System.out.println(user.getUsername());
        }
    }
    

    多次查询,只执行一次 SQL。但是注意,如果开启了一个新的 SqlSession,则新的 SqlSession 无法就是之前的缓存,必须是同一个 SqlSession 中,缓存才有效。

    MyBatis 二级缓存

    Mybatis 二级缓存是多个 SqlSession 共享的,其作用域是 mapper 的同一个 namespace,不同的 sqlSession 两次执行相同 namespace 下的 sql 语句且向 sql 中传递参数也相同即最终执行相同的 sql 语句,第一次执行完毕会将数据库中查询的数据写到缓存(内存),第二次会从缓存中获取数据将不再从数据库查询,从而提高查询效率。Mybatis 默认没有开启二级缓存需要在 setting 全局参数中配置开启二级缓存。

    更多干货请移步:https://antoniopeng.com

  • 相关阅读:
    SPOJ GSS4 Can you answer these queries IV ——树状数组 并查集
    SPOJ GSS3 Can you answer these queries III ——线段树
    SPOJ GSS2 Can you answer these queries II ——线段树
    SPOJ GSS1 Can you answer these queries I ——线段树
    BZOJ 2178 圆的面积并 ——Simpson积分
    SPOJ CIRU The area of the union of circles ——Simpson积分
    HDU 1724 Ellipse ——Simpson积分
    HDU 1071 The area ——微积分
    HDU 4609 3-idiots ——FFT
    BZOJ 2194 快速傅立叶之二 ——FFT
  • 原文地址:https://www.cnblogs.com/antoniopeng/p/14372256.html
Copyright © 2011-2022 走看看