1. 程式人生 > >spring boot(9)-mybatis關聯對映

spring boot(9)-mybatis關聯對映

一對多

查詢type表的某一條資料,並且要同時查出所有typeid與之配置的user,最終要得到一個以下型別的Type物件
public class Type {
	String id;
	String name;
	List<User> users;
dao層
	@Select("select * from user where typeid = #{typeid}")
	public List<User> findUserById(String typeid);
	
	@Results({
			@Result(property="id",column="id"),
			//users對映List<User> users,
[email protected]
是呼叫關聯查詢方法,"id"是關聯查詢條件,FetchType.LAZY是延遲載入 @Result(property="users",column="id", [email protected](select="hello.dao.MybatisDao.findUserById",fetchType=FetchType.LAZY)) }) @Select("select * from type where id=#{id}") public Type findTypeById(String id);
注意,如果省略第一個@Result, 查出來的type物件id是null,因為第二個@Result使用關聯查詢時把column="id"對映給了property="users"。
service層
		Type type = mybatisDao.findTypeById("1");
		System.out.println("延遲載入");
		type.getUsers();

因為設定了fetchType=FetchType.LAZY,mybatisDao.findTypeById("1")只會查詢type表,當訪問type.getUsers()時才會查詢其關聯表。

其它關聯

一對一:把上面的[email protected]換成[email protected],其他原理是一樣的
多對多:把多個欄位對映成[email protected],就是多對多了

多對一:把上面dao方法的返回值從Type換成List<Type>

JAVA註解的侷限性

通過SQL日誌可以看到,前面的一對多關聯查詢實際上執行了兩次select,這就是hibernate中典型的n+1問題。假設我現在type表中有三條記錄,我要查出所有的type及其對應的user物件,最終得到一個List<Type>,查詢過程是這樣的
一共執行了四次查詢,一次查type表,因為有三條記錄,所以查了三次user表,以此來填充三個type物件的List<User> users屬性。如果type表中有幾百條資料,而且還有上十個表進行關聯查詢,結果無法設想。在傳統的xml配置方式中,是可以用一條SQL查出無限層巢狀的關聯關係的。不過mybatis官方做出了一個說明,由於java註解的侷限性,不支援那種對映方式。所以,如果想只用一條SQL查出關聯對映,必須借住xml

xml無限層巢狀對映

這裡以三層巢狀為例,以實現前端的三級選單樹。這是一個tree表,pid是其上級選單的id。


要得到的查詢結果Tree物件,這個物件是可以無限遞迴的
public class Tree {
	String id;
	String name;
	List<Tree> child;
dao
@Mapper
public interface TreeDao {
	@ResultMap("tree")
	@Select("SELECT p1.id,p1.name,p2.id id2,p2.name name2,p3.id id3,p3.name name3 "
			+ "FROM tree p1,tree p2,tree p3 WHERE p1.id=p2.pid AND p2.id=p3.pid")
	public List findTree();  
這個SQL在資料庫中的查詢結果是這樣的,可以發現前四個欄位是一樣的,而且都是冗餘資料,如果用java註解的關聯查詢是不會這樣的
@ResultMap("tree"):對映結果集id是tree,前面說了,這個對映要在xml中配置application.properties檔案中新增配置
#指定xml對映檔案的路徑
mybatis.mapper-locations=classpath:hello/mapper/*
hello.mapper.TreeMapper.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">
<!-- 對映dao -->
<mapper namespace="hello.dao.TreeDao">
  <!-- 結果集型別 -->
  <resultMap id="tree" type="hello.pojo.Tree">
    <!-- 對映欄位 -->
    <result column="id"  property="id" />
    <result column="name"  property="name" />
    <!-- 巢狀第二張表 -->
    <collection  property="child" ofType="hello.pojo.Tree" >  
        <id column="id2" property="id" />
	<result column="name2" property="name" />
	<!-- 巢狀第三張表 -->
	<collection  property="child" ofType="hello.pojo.Tree" >  
        	<id column="id3" property="id" />
		<result column="name3" property="name" />
        </collection>  	 
     </collection>  	
  </resultMap>
</mapper>
這裡只是配置一個巢狀對映,在dao方法中通過@ResultMap("tree")使用這個對映。最終查詢結果會對映成一個Tree物件,通過spring mvc轉換為json結果如下,在一些前端框架中,實現樹形選單就是需要用這種結構的JSON資料賦值
[
  {
    "id": "1",
    "name": "一級樹",
    "child": [
      {
        "id": "11",
        "name": "二級樹-1",
        "child": [
          {
            "id": "112",
            "name": "三級樹-1",
            "child": null
          },
          {
            "id": "113",
            "name": "三級樹-2",
            "child": null
          }
        ]
      }
    ]
  }
]

使用JAVA註解還是XML

XML執行一條SQL語句,並不是一定比JAVA註解執行多條SQL效能更優一條SQL:關聯的表越多,笛卡爾積越大,查詢結果的冗餘資料也越多多條SQL:只需單表查詢,如果做好索引查詢效率會非常高,查詢結果也沒有冗餘 。在現實中,如果使用其中一種方式的效能較低,則可以償試另一方式進行測試,同時還要考慮資料庫優化策略

相關推薦

spring boot(9)-mybatis關聯對映

一對多查詢type表的某一條資料,並且要同時查出所有typeid與之配置的user,最終要得到一個以下型別的Type物件public class Type { String id; String n

spring boot + gradle + mybatis

下載速度 -s 就會 如何 tom cnblogs server lec null 使用intelliJ創建 spring boot + gradle + mybatis站點 Spring boot作為快速入門是不錯的選擇,現在似乎沒有看到大家寫過spring bo

idea spring-boot gradle mybatis

apply 表名 ngs exc back cte org pty ram 使用工具idea 2017.2開發,gradle構建項目,使用的技術有spring-boot、mybatis 1、新建項目

spring cloud + spring boot + springmvc+mybatis分布式微服務雲架構

框架源碼 .html gmv tor 分布式 ring ast log reac 做一個微服務架構需要的技術整理: View: H5、Vue.js、Spring Tag、React、angularJs Spring Boot/Spring Cloud:Zuul、Ribbon

spring boot整合mybatis深坑之c3p0的詳細配置

text context ati reat source ast type fig oot 項目地址:https://gitee.com/zhangjunqing/spring-boot/tree/master/springboot-mybatis-notice 本人在c3

Spring Boot使用MyBatis 3打印SQL的配置

rate tail omap logback ets label color inf ons 普通Spring下的XML文件配置: <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE config

spring boot配置mybatis和事務管理

生成 很多 -s 順序 south 位置 ron 技術 username spring boot配置mybatis和事務管理 一、spring boot與mybatis的配置 1.首先,spring boot 配置mybatis需要的全部依賴如下: <!-- Spri

spring boot 整合mybatis

參考 plugins odin system stack name incr xmlns xsd 參考: http://blog.csdn.net/saytime/article/details/74783296 spring boot可以使用全註解的方式進行開發,極大的提

spring boot整合mybatis+mybatis-plus

可靠 nic false system ttr .post 代碼生成 -i filters Spring boot對於我來說是一個剛接觸的新東西,學習過程中,發現這東西還是很容易上手的,Spring boot沒配置時會默認使用Spring data jpa,這東西可以說一個

企業分布式微服務雲SpringCloud SpringBoot mybatis (十三)Spring Boot整合MyBatis

ech 字段 osc 操作 with public assert 連接 ref Spring中整合MyBatis就不多說了,最近大量使用Spring Boot,因此整理一下Spring Boot中整合MyBatis的步驟。搜了一下Spring Boot整合MyBatis的文

Spring Boot整合MyBatis學習總結

Spring Boot MyBatis druid數據源 druid sql監控 公司的很多項目都陸陸續續引入了Spring Boot,通過對Spring Boot的接觸了解發現其真的是大大地簡化了開發、簡化了依賴配置,很多功能註解一下就可以實現,真的是太方便了。下面記錄了一個Sp

Spring boot 配置 mybatis xml和動態SQL

star too conn -- 動態 div nec output out 1.pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="

spring bootmybatis使用Map返回時,當值為空時屬性也會沒有(轉)

call pri per n-n spring fig setter 解決 strong 使用spring boot加mybatis時,設置Map返回,當值為空時屬性也會沒有,就會報錯 在application.properties中加入下面配置,將會解決這個問題。

idea整合 spring boot jsp mybatis

pom rep tput 1.8 iba ring color bat maven spring boot 開發起來確實要簡單許多 ,spring boot 包含了 spring mvc ;內置tomcat ;啟動只需要主方法即可 1.使用idea新建一個sp

spring boot整合mybatis

tis ott 最簡 boot.s driver 大連 ins pla configure spring boot本來可以使用jpa進行數據庫操作,但是考慮到jpa的資料比較少,學習成本比較大,不是所有的人都可以十分了解,因此考慮采用mybatis來進行數據庫操作。 1、新

spring boot-9.對springMVC的支持

mat org dia pro eml dep 高級 pen 格式 1.thymeleaf spring boot 推薦的模板引擎是thymeleaf。spring boot 的自動配置已經默認配置好了themleaf,只要導入themleaf的Starter就可以了。

SpringBoot自學教程 | 第四篇:Spring Boot整合mybatis

整合 com 字段 apach param pack image ice rac   引入依賴   1:在pom文件引入mybatis-spring-boot-starter的依賴: 1 <dependency> 2 <groupId>

spring boot 整合mybatis:org.apache.ibatis.binding.BindingException: Invalid bound statement (not found):

pri ssp path 內容 方案 sta 問題 xmapp not 最近在學習SpringBoot,遇到些異常情況: 1、異常信息 org.apache.ibatis.binding.BindingException: Invalid bound statement (

spring bootmybatis使用註解進行模糊查詢

cat 遇到 google 使用註解 ring list bat prop ber 小白一枚,spring boot 2.0.5在使用mybatis進行註解模糊查詢時遇到一些低級的錯誤,現記錄下來錯誤示例:“select * from user where name lik

spring boot 整合mybatis(好用!!!!)

com true pla 12px 保密 center 性別 request context springboot整合mybatis 1.pom依賴 <!-- 引入freeMarker的依賴包. --> <dependency>