亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

您的位置:首頁技術文章
文章詳情頁

老生常談 MyBatis 復雜查詢

瀏覽:3日期:2023-10-20 11:36:30
一對一查詢

在實際開發中,經常會遇到一對一查詢,一對多查詢等。這里我們先來看一對一查詢。例如:每本書都有一個作者,作者都有自己的屬性,根據這個,我來定義兩個實體類:

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 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 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 type='com.antonio.hello.mybatis.entity.Book'> <id column='id' property='id'/> <result column='name' property='name'/> </resultMap> <resultMap 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 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 type='com.antonio.hello.mybatis.entity.Book'> <id column='id' property='id'/> <result column='name' property='name'/></resultMap><resultMap 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 resultMap='BookWithAuthor2'> select * from book where id=#{id};</select><select 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 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 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 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 resultMap='UserWithRole'> select * from user where id=#{id};</select><select 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 全局參數中配置開啟二級緩存。

到此這篇關于老生常談 MyBatis 復雜查詢的文章就介紹到這了,更多相關MyBatis 復雜查詢內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Mybatis 數據庫
相關文章:
主站蜘蛛池模板: 国产一区二区视频在线观看 | 182午夜在线观看 | 一级日本特黄毛片视频 | 能可以直接看的av网址 | 欧美变态一级毛片 | 影音先锋5566手机在线播放 | 久久九九国产精品怡红院 | 亚洲一区二区三区国产精品 | 国产成人18黄网站在线观看网站 | 中文字幕欧美亚洲 | 精品视频999 | 日韩美一区二区三区 | 国产精品网站 夜色 | 亚洲精品国产福利 | 奇米影视久久777中文字幕 | 国产换爱交换乱理伦片的功能 | 香蕉视频99 | 99国产精品免费视频观看 | 毛片6 | 国产高清好大好夹受不了了 | 小明看看成人免费视频 | 青青草在线免费观看 | 在线日韩视频 | 上海一级毛片 | 精品无人区乱码一区二区三区手机 | 亚洲综合无码一区二区 | 国产激情网| 色播影院性播12306影视 | 三级午夜宅宅伦不卡在线 | 亚洲国产美女在线观看 | 免费看的黄色 | 久久黄色影片 | 国产精品永久免费 | 欧洲美女高清一级毛片 | 国产精品免费播放 | 亚洲一区区 | 亚洲综合精品香蕉久久网 | 黄黄视频在线观看 | 国产成人精品久久一区二区三区 | 91精选| 亚洲欧美日韩一区高清中文字幕 |