1. 程式人生 > >mybatis學習筆記(六)- MyBatis 對映檔案(select)

mybatis學習筆記(六)- MyBatis 對映檔案(select)

1. select 返回 List & 記錄封裝 map

  1. 介面 EmployeeMapper
public interface EmployeeMapper {
    //多條記錄封裝一個map:Map<Integer,Employee>:鍵是這條記錄的主鍵,值是記錄封裝後的javaBean
	//@MapKey:告訴mybatis封裝這個map的時候使用哪個屬性作為map的key
	@MapKey("lastName")
	public Map<String, Employee> getEmpByLastNameLikeReturnMap
(String lastName); //返回一條記錄的map;key就是列名,值就是對應的值 public Map<String, Object> getEmpByIdReturnMap(Integer id); public List<Employee> getEmpsByLastNameLike(String lastName); }
  1. 對映檔案 EmployeeMapper.xml
<mapper namespace="www.xq.mybatis.dao.EmployeeMapper">
    <!--public Map<Integer, Employee> getEmpByLastNameLikeReturnMap(String lastName);  -->
<select id="getEmpByLastNameLikeReturnMap" resultType="www.xq.mybatis.bean.Employee"> select * from tbl_employee where last_name like #{lastName} </select> <!--public Map<String, Object> getEmpByIdReturnMap(Integer id); --> <select id="getEmpByIdReturnMap" resultType
="map">
select * from tbl_employee where id=#{id} </select> <!-- public List<Employee> getEmpsByLastNameLike(String lastName); --> <!--resultType:如果返回的是一個集合,要寫集合中元素的型別 --> <select id="getEmpsByLastNameLike" resultType="www.xq.mybatis.bean.Employee"> select * from tbl_employee where last_name like #{lastName} </select> </mapper>
  1. 測試
@Test
	public void test04() throws IOException{
		
		SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
		//1、獲取到的SqlSession不會自動提交資料
		SqlSession openSession = sqlSessionFactory.openSession();
		
		try{
		EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
			//Employee employee = mapper.getEmpByIdAndLastName(1, "tom");
			/*Map<String, Object> map = new HashMap<>();
			map.put("id", 2);
			map.put("lastName", "Tom");
			map.put("tableName", "tbl_employee");
			Employee employee = mapper.getEmpByMap(map);
			
			System.out.println(employee);*/
			
			List<Employee> like = mapper.getEmpsByLastNameLike("%e%");
			for (Employee employee : like) {
				System.out.println(employee);
			}
			
			/*Map<String, Object> map = mapper.getEmpByIdReturnMap(1);
			System.out.println(map);*/
			/*Map<String, Employee> map = mapper.getEmpByLastNameLikeReturnMap("%r%");
			System.out.println(map);*/
			}
			}finally{
			openSession.close();
		}
	}

2. resultMap 自定義結果對映規則

  1. 為了方便測試,我們新建一個 dao 介面 EmployeeMapperPlus
public interface EmployeeMapperPlus {

	public Employee getEmpById(Integer id);
}
  1. 新建一個對映檔案 EmployeeMapperPlus.xml
<mapper namespace="www.xq.mybatis.dao.EmployeeMapperPlus">

	<!--自定義某個javaBean的封裝規則
	type:自定義規則的Java型別
	id:唯一id方便引用
	  -->
	<resultMap type="www.xq.mybatis.bean.Employee" id="MySimpleEmp">
		<!--指定主鍵列的封裝規則
		id定義主鍵會底層有優化;
		column:指定哪一列
		property:指定對應的javaBean屬性
		  -->
		<id column="id" property="id"/>
		<!-- 定義普通列封裝規則 -->
		<result column="last_name" property="lastName"/>
		<!-- 其他不指定的列會自動封裝:我們只要寫resultMap就把全部的對映規則都寫上。 -->
		<result column="email" property="email"/>
		<result column="gender" property="gender"/>
	</resultMap>
	
	<!-- resultMap:自定義結果集對映規則;  -->
	<!-- public Employee getEmpById(Integer id); -->
	<select id="getEmpById"  resultMap="MySimpleEmp">
		select * from tbl_employee where id=#{id}
	</select>
</mapper>
  1. 測試
@Test
public void test05() throws IOException{
	SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
	SqlSession openSession = sqlSessionFactory.openSession();
	try{
		EmployeeMapperPlus mapper = openSession.getMapper(EmployeeMapperPlus.class);
		Employee empById = mapper.getEmpById(1);
		System.out.println(empById);
	}finally{
		openSession.close();
	}
}

3. 關聯查詢

3.1. 環境搭建

3.1.1. 在 Employee 類中加入 private Department dept; 以及其的get,set方法。

3.1.2. 建立 Department 類

package www.xq.mybatis.bean;

import java.util.List;

public class Department {
	
	private Integer id;
	private String departmentName;
	private List<Employee> emps;
	
	
	
	public List<Employee> getEmps() {
		return emps;
	}
	public void setEmps(List<Employee> emps) {
		this.emps = emps;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getDepartmentName() {
		return departmentName;
	}
	public void setDepartmentName(String departmentName) {
		this.departmentName = departmentName;
	}
	@Override
	public String toString() {
		return "Department [id=" + id + ", departmentName=" + departmentName
				+ "]";
	}
}

3.1.3. 在 mybatis 中建立 tbl_dept 表並在 tbl_employee 中新增一列,建立外來鍵關聯。

CREATE TABLE tbl_dept(
id INT(11) PRIMARY KEY AUTO_INCREMENT,
dept_name VARCHAR(255)
)

ALTER TABLE tbl_employee ADD COLUMN d_id INT(11);

ALTER TABLE tbl_employee ADD CONSTRAINT fk_emp_dept
FOREIGN KEY(d_id) REFERENCES tbl_dept(id) 

3.2. 級聯屬性封裝結果&association定義關聯物件封裝規則

3.2.1. EmployeeMapperPlus 介面中加入:

    public Employee getEmpAndDept(Integer id);

3.2.2. EmployeeMapperPlus.xml

    <!-- 
	場景一:
		查詢Employee的同時查詢員工對應的部門
		Employee===Department
		一個員工有與之對應的部門資訊;
		id  last_name  gender    d_id     did  dept_name (private Department dept;)
	 -->
	 
	 
	<!--
		聯合查詢:級聯屬性封裝結果集
	  -->
	<resultMap type="www.xq.mybatis.bean.Employee" id="MyDifEmp">
		<id column="id" property="id"/>
		<result column="last_name" property="lastName"/>
		<result column="gender" property="gender"/>
		<result column="did" property="dept.id"/>
		<result column="dept_name" property="dept.departmentName"/>
	</resultMap>


	<!-- 
		使用association定義關聯的單個物件的封裝規則;
	 -->
	<resultMap type="www.xq.mybatis.bean.Employee" id="MyDifEmp2">
		<id column="id" property="id"/>
		<result column="last_name" property="lastName"/>
		<result column="gender" property="gender"/>
		
		<!--  association可以指定聯合的javaBean物件
		property="dept":指定哪個屬性是聯合的物件
		javaType:指定這個屬性物件的型別[不能省略]
		-->
		<association property="dept" javaType="www.xq.mybatis.bean.Department">
			<id column="did" property="id"/>
			<result column="dept_name" property="departmentName"/>
		</association>
	</resultMap>
	<!--  public Employee getEmpAndDept(Integer id);-->
	<select id="getEmpAndDept" resultMap="MyDifEmp">
		SELECT e.id id,e.last_name last_name,e.gender gender,e.d_id d_id,
		d.id did,d.dept_name dept_name FROM tbl_employee e,tbl_dept d
		WHERE e.d_id=d.id AND e.id=#{id}
	</select>

3.2.3. 測試

@Test
	public void test05() throws IOException{
		SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
		SqlSession openSession = sqlSessionFactory.openSession();
		try{
			EmployeeMapperPlus mapper = openSession.getMapper(EmployeeMapperPlus.class);
			Employee empAndDept = mapper.getEmpAndDept(1);
			System.out.println(empAndDept);
			System.out.println(empAndDept.getDept());
		}finally{
			openSession.close();
		}
		
		
	}

3.3. association分步查詢

3.3.1. 建立 DepartmentMapper 介面

package www.xq.mybatis.dao;
import www.xq.mybatis.bean.Department;
public interface DepartmentMapper {
	public Department getDeptById(Integer id);
}

3.3.2. 建立對映檔案 DepartmentMapper.xml

<mapper namespace="www.xq.mybatis.dao.DepartmentMapper">
	<!--public Department getDeptById(Integer id);  -->
	<select id="getDeptById" resultType="www.xq.mybatis.bean.Department">
		select id,dept_name departmentName from tbl_dept where id=#{id}
	</select>
</mapper>

3.3.3. EmployeeMapperPlus 介面中加入

    public Employee getEmpByIdStep(Integer id);

3.3.4. EmployeeMapperPlus.xml 中加入

<!-- 使用association進行分步查詢:
		1、先按照員工id查詢員工資訊
		2、根據查詢員工資訊中的d_id值去部門表查出部門資訊
		3、部門設定到員工中;
	 -->
	 
	 <!--  id  last_name  email   gender    d_id   -->
	 <resultMap type="www.xq.mybatis.bean.Employee" id="MyEmpByStep">
	 	<id column="id" property="id"/>
	 	<result column="last_name" property="lastName"/>
	 	<result column="email" property="email"/>
	 	<result column="gender" property="gender"/>
	 	<!-- association定義關聯物件的封裝規則
	 		select:表明當前屬性是呼叫select指定的方法查出的結果
	 		column:指定將哪一列的值傳給這個方法
	 		
	 		流程:使用select指定的方法(傳入column指定的這列引數的值)查出物件,並封裝給property指定的屬性
	 	 -->
 		<association property="dept" 
	 		select="www.xq.mybatis.dao.DepartmentMapper.getDeptById"
	 		column="d_id">
 		</association>
	 </resultMap>
	 <!--  public Employee getEmpByIdStep(Integer id);-->
	 <select id="getEmpByIdStep" resultMap="MyEmpByStep">
	 	select * from tbl_employee where id=#{id}
	 </select>

3.3.5. 測試

@Test
	public void test05() throws IOException{
		SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
		SqlSession openSession = sqlSessionFactory.openSession();
		try{
			EmployeeMapperPlus mapper = openSession.getMapper(EmployeeMapperPlus.class);
            Employee employee = mapper.getEmpByIdStep(1);
			System.out.println(employee);
			System.out.println(employee.getDept());
			}finally{
			openSession.close();
		}
	}

3.4. 分步查詢&延遲載入

  • 可以使用延遲載入(懶載入);(按需載入)
    • Employee==>Dept:
      我們每次查詢Employee物件的時候,都將一起查詢出來。
      部門資訊在我們使用的時候再去查詢;
      分段查詢的基礎之上加上兩個配置:
  • 只需在 mybatis-config.xml 檔案的 settings 標籤中加入一下設定
<!--顯示的指定每個我們需要更改的配置的值,即使他是預設的。防止版本更新帶來的問題  -->
		<setting name="lazyLoadingEnabled" value="true"/>
		<setting name="aggressiveLazyLoading" value="false"/>

3.5. collection 定義關聯集合封裝規則&分步查詢&延遲載入

3.5.1. 在 DepartmentMapper 中加入

public Department getDeptByIdPlus(Integer id);

public Department getDeptByIdStep(Integer id);

3.5.2. 在 DepartmentMapper.xml 中加入

<!--巢狀結果集的方式,使用collection標籤定義關聯的集合型別的屬性封裝規則  -->
	<resultMap type="www.xq.mybatis.bean.Department" id="MyDept">
		<id column="did" property="id"/>
		<result column="dept_name" property="departmentName"/>
		<!-- 
			collection定義關聯集合型別的屬性的封裝規則 
			ofType:指定集合裡面元素的型別
		-->
		<collection property="emps" ofType="www.xq.mybatis.bean.Employee">
			<!-- 定義這個集合中元素的封裝規則 -->
			<id column="eid" property="id"/>
			<result column="last_name" property="lastName"/>
			<result column="email" property="email"/>
			<result column="gender" property="gender"/>
		</collection>
	</resultMap>
	<!-- public Department getDeptByIdPlus(Integer id); -->
	<select id="getDeptByIdPlus" resultMap="MyDept">
		SELECT d.id did,d.dept_name dept_name,
				e.id eid,e.last_name last_name,e.email email,e.gender gender
		FROM tbl_dept d
		LEFT JOIN tbl_employee e
		ON d.id=e.d_id
		WHERE d.id=#{id}
	</select>
	
	<!-- collection:分段查詢 -->
	<resultMap type="www.xq.mybatis.bean.Department" id="MyDeptStep">
		<id column="id" property="id"/>
		<id column="dept_name" property="departmentName"/>
		<collection property="emps" 
			select="www.xq.mybatis.dao.EmployeeMapperPlus.getEmpsByDeptId"
			column="{deptId=id}" fetchType="lazy"></collection>
	</resultMap>
	<!-- public Department getDeptByIdStep(Integer id); -->
	<select id="getDeptByIdStep" resultMap="MyDeptStep">
		select id,dept_name from tbl_dept where id=#{id}
	</select>

3.5.3. 測試

@Test
	public void test06() throws IOException{
		SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
		SqlSession openSession = sqlSessionFactory.openSession();
		
		try{
			DepartmentMapper mapper = openSession.getMapper(DepartmentMapper.class);
			//測試 collection 定義關聯集合封裝規則
			/*Department department = mapper.getDeptByIdPlus(1);
			System.out.println(department);
			System.out.println(department.getEmps());*/
			//測試 collection 分步查詢和延遲載入
			Department deptByIdStep = mapper.getDeptByIdStep(1);
			System.out.println(deptByIdStep.
            
           

相關推薦

mybatis學習筆記- MyBatis 對映檔案(select)

1. select 返回 List & 記錄封裝 map 介面 EmployeeMapper public interface EmployeeMapper { //多條記錄封裝一個map:Map<Integer,Employee>:鍵

JavaEE--Mybatis學習筆記--查詢緩存

原則 主配置文件 enabled app 目錄 session共享 證明 bsp 更新 查詢緩存   查詢緩存的使用,主要是為了提高查詢訪問速度。將用戶對同一數據的重復查詢過程簡化,不再每次均從數據庫查詢獲取結果數據,從而提高訪問速度。    左為執行原理示意圖 右為執

Mybatis 學習筆記——延遲載入

一、延遲載入介紹   延遲載入的目的是為了加快查詢速度,提升資料庫效能。對於一個複雜的查詢sql,在業務許可的情況下,我們可以用兩種方式來提升查詢速度(Mybatis環境),讓資料庫的效能蹭蹭的往上提升。第一種是將這個複查查詢分成兩個 statement 先執行

MyBatis學習筆記mybatis-config.xml都有哪些配置之環境配置與對映

環境配置(environments),其中還可以配置事物,專案中大概也不會用到。 <environments default="development"> <environment id="development"> <t

mybatis學習筆記- MyBatis 對映檔案(引數處理)

注意:本篇筆記內容承接上一篇 引數處理 1. 單個引數&多個引數&命名引數 簡介 單個引數:mybatis不會做特殊處理, #{引數名/任意名}:取出引數值。 多個引數:mybatis會做特殊處理。

mybatis學習筆記- MyBatis 對映檔案(增刪改)

1. MyBatis 對映檔案章節的工程目錄 對映檔案指導著MyBatis如何進行資料庫增刪改查, 有著非常重要的意義 2. 增刪改的使用 2.1. 建立 Employee 類 注意:如果給類建立有參構造器時,一定給它一個無參構造器 package www.x

Mybatis學習筆記--動態sql拼接

介紹 通過mybatis提供的各種標籤方法實現動態拼接sql Mybatis動態sql---<sql>與<include> <!-- 使用include標籤載入sql片段;refid是sql片段id --> <sql id="select"&

Mybatis學習筆記-Mybatis配置檔案對映檔案詳解

一、Mybatis配置檔案詳解 以下是mybatis.xml檔案,提倡放在src目錄下,檔名任意 <?xml version="1.0" encoding="UTF-8"?> <

MyBatis學習筆記一對多的關聯查詢和傳遞多個引數

首發於我的部落格 和尚的部落格 本文講解一對多的關聯查詢,傳遞多個引數。 1.傳遞多個引數 當你的形參傳遞>1個的時候,parameterType不寫,讓其自動處理 #{值},預設為arg0,arg1…..或param1,param2,,,

mybatis學習筆記使用generator生成mybatis基礎配置程式碼和目錄結構

建立maven專案 <span style="font-size:14px;"><project xmlns="http://maven.apache.org/POM/4.0.0"

Mybatis學習筆記——配置檔案

本部落格原始碼下載:戳我一下 Mybatis學習筆記彙總:戳我一下 一、配置檔案內容 SqlMapConfig.xml中配置的內容和順序如下: properties(屬性) settings(全域性配置引數) typeAliases(類型別名) t

MyBatis學習筆記mybatis-config.xml都有哪些配置之typeAliases與plugins

類型別名(typeAlicases) 在mybatis-config.xml配置檔案中加入類描述 <typeAliases> <typeAlias type="org.mybatis.example.User" alias="User" />

mybatis學習筆記- 全域性配置檔案

1. 引入 dtd 約束 為什麼要引入 dtd 約束 由於 mybatis 的全域性配置檔案很重要,我們學習 mybatis 必須要用到,但是如果不引入 dtd 約束,我們在這個檔案裡將不會得到程式碼提示,會給我們開發帶來極大不便。 引入方法 聯網情況下:直接點

Mybatis 學習筆記——Mybatis 逆向工程的三種方法

Mybatis 逆向工程   逆向工程通常包括由資料庫的表生成 Java 程式碼 和 通過 Java 程式碼生成資料庫表。而Mybatis 逆向工程是指由資料庫表生成 Java 程式碼。   Mybaits 需要程式設計師自己編寫 SQL 語句,但是 Myba

《自己動手寫java虛擬機器》學習筆記-----解析class檔案java

專案地址:https://github.com/gongxianshengjiadexiaohuihui 註釋都寫的很清楚,有一些概念問題,請參考go版本的實現 目錄結構 首先是位元組轉換工具,因為java和go的類庫不同,另外需注意class檔案是大端儲存方式(高位元組放低地址,

Mybatis 學習筆記——關聯對映關係一對一,一對多

一、背景知識    在介紹對映關係之前需要我們對 resultMap 要足夠了解。在 resultMap 中有如下節點可配置: id :唯一標識列,column 為資料庫ID列,property為 POJO 的id屬性,注意在查詢出的結果集中每一列都必須不一樣

MyBatis學習筆記——輸入(parameterType)與輸出(resultType、resultMap)對映

一、輸入對映 parameterType 在MyBatis中,我們通過parameterType屬性完成輸入型別對映。這個屬性可接收普通型別也可以接收一個pojo物件。那麼如果我們想要通過這個屬性對映兩個或多個pojo物件時應該怎麼做呢? 這個時候我們就可以運用包裝類來解決

Mybatis 學習筆記——關聯對映關係多對多

三、多對多對映關係 1. 需求:查詢使用者及商品資訊 2. POJO類 /mybatis01/src/com/po/User.java package com.po; import java.util.Date; import java.util.List;

Mapper.xml對映檔案---Mybatis學習筆記

Mapper.xml對映檔案中定義了操作資料庫的sql,每個sql是一個statement,對映檔案是mybatis的核心。 parameterType(輸入型別) 1.#{}與${} #{}實現的是向prepareStatement中的預處理語句

mybatis學習筆記 多pojo,複雜對映

現在在資料庫增加兩張表blog與comment ,即部落格與評論表。 CREATE TABLE `blog` ( `id` int(11) NOT NULL default '0', `title` varchar(255) default NULL, `co