MyBatis框架——關係映射(一對多、多對多、多對一查詢)

關係映射 

1、映射(多)對1、(一)對一的關聯關係

1).使用列的別名
①.若不關聯數據表,則能夠獲得關聯對象的id屬性
②.若還但願獲得關聯對象的其它屬性。則必須關聯其它的數據表java

1.建立表:

員工表:sql

DROP TABLE IF EXISTS `tbl_employee`;

CREATE TABLE `tbl_employee` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(255) DEFAULT NULL,
`gender` char(1) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`d_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_emp_dept` (`d_id`),
CONSTRAINT `fk_emp_dept` FOREIGN KEY (`d_id`) REFERENCES `tbl_dept` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; 


部門表:mybatis

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

 


2.建立相應的實體類和Mapper接口!

3.寫關聯的SQL語句

SELECT e.`id` id , e.`user_name` user_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 = 1

  

4.在sql映射文件中寫映射sql語句

方法一:【聯合查詢:級聯屬性封裝結果集】

<!-- 聯合查詢:級聯屬性封裝結果集 -->
<resultMap type="com.neuedu.entity.Employee" id="getEmployeeAndDeptMap">
<id column="id" property="id"/>
<result column="user_name" property="userName"/>
<result column="gender" property="gender"/>
<result column="email" property="email"/>
<result column="did" property="depart.id"/>
<result column="dept_name" property="depart.deptName"/>
</resultMap>

<!-- public Employee getEmployeeAndDept(Integer id); -->
<select id="getEmployeeAndDept" resultMap="getEmployeeAndDeptMap">
SELECT e.`id` id , e.`user_name` user_name, e.`gender` gender,e.`email` email,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> 

注意:即便使用resultMap來映射,對於「對一」關聯關係能夠不使用association
app

 

方法二:【使用association來定義關聯對象的規則,[比較正規的,推薦的方式]】

<!-- 聯合查詢:使用association封裝結果集 -->
<resultMap type="com.neuedu.entity.Employee" id="getEmployeeAndDeptMap">
<id column="id" property="id"/>
<result column="user_name" property="userName"/>
<result column="gender" property="gender"/>
<result column="email" property="email"/>
<!-- 
association能夠指定聯合的javaBean對象
property="depart":指定哪一個屬性是聯合的對象
javaType:指定這個屬性對象的類型【不能省略】
-->
<association property="depart" javaType="com.neuedu.entity.Department">
<id column="did" property="id"/>
<result column="dept_name" property="deptName"/>
</association>
</resultMap>

<!-- public Employee getEmployeeAndDept(Integer id); -->
<select id="getEmployeeAndDept" resultMap="getEmployeeAndDeptMap">
SELECT e.`id` id , e.`user_name` user_name, e.`gender` gender,e.`email` email,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>



方法三:[上述結果至關於使用嵌套結果集的形式]【咱們這裏還可使用Association進行分步查詢】:

<!-- 
使用association進行分步查詢 
1.先按照員工id查詢員工信息
2.根據查詢員工信息中d_id值取部門表查出部門信息
3.部門設置到員工中:
-->
<select id="getDepartById" resultType="com.neuedu.entity.Department">
SELECT id ,dept_name deptName FROM tbl_dept WHERE id = #{id}
</select>
<resultMap type="com.neuedu.entity.Employee" id="myEmpByStep">
<id column="id" property="id"/>
<result column="user_name" property="userName"/>
<result column="gender" property="gender"/>
<result column="email" property="email"/>
<!-- 
association定義關聯對象的封裝規則
select:代表當前屬性是調用指定的方法查出的結果
column:指定將哪一列的值傳給這個方法

流程:使用select指定的方法(傳入column指定的這列參數的值)查出對象,並封裝給property指定的屬性。
-->
<association property="depart" select="getDepartById" column="d_id"></association>
</resultMap>
<!-- public Employee getEmpAndDept(Integer id); -->
<select id="getEmpAndDept" resultMap="myEmpByStep">
select * from tbl_employee where id =#{id}
</select>


5.編寫測試用例

public class TestMyBatis {
private SqlSession openSession = null;

@Test
public void testGetEmployee(){
  EmployeeMapperPlus mapper = openSession.getMapper(EmployeeMapperPlus.class);
  Employee employee = mapper.getEmployeeAndDept(1);
  System.out.println(employee);
}

@Before
public void testBefore() throws IOException{
  String resource = "mybatis-config.xml";
  InputStream inputStream = Resources.getResourceAsStream(resource);
  SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  openSession= sqlSessionFactory.openSession();
}

@After
public void testAfter(){
  openSession.commit();
  openSession.close();
}

}

  


補充:懶加載機制【按需加載,也叫懶加載】:

<!-- 
在分步查詢這裏,咱們還要講到延遲加載:
Employee === > Dept:
咱們每次查詢Employee對象的時候,都將關聯的對象查詢出來了。
而咱們想能不能我在須要部門信息的時候,再去查詢,不須要的時候就不用查詢了。
答案:能夠的
咱們只須要在分步查詢的基礎之上加上兩個配置:
1.在mybatis的全局配置文件中加入兩個屬性:
<settings>
  <setting name="mapUnderscoreToCamelCase" value="true"/>
  <!-- 開啓懶加載機制 ,默認值爲true-->
  <setting name="lazyLoadingEnabled" value="true"/>
  <!-- 開啓的話,每一個屬性都會直接所有加載出來;禁用的話,只會按需加載出來 -->
  <setting name="aggressiveLazyLoading" value="false"/>
</settings>

-->

  

測試:
測試

@Test
public void testGetEmployee(){
EmployeeMapperPlus mapper = openSession.getMapper(EmployeeMapperPlus.class);
Employee employee = mapper.getEmpAndDept(1);
System.out.println(employee.getUserName());
}

 


此時:能夠看到這裏只發送了一條SQL語句。

注意:上面咱們上面若是關聯的是一個對象,咱們還可使用association標籤,若是咱們關聯的是一個集合,
那麼該使用誰呢?
ui

2、映射對多的關聯關係

場景二:查詢部門的時候,將部門對應的全部員工信息也查詢出來,註釋在DepartmentMapper.xml中
this

第一種:使用collection嵌套結果集的方式:

1.修改Department實體類【添加Employee集合,併爲該集合提供getter/setter方法】

public class Department {
private Integer id;
private String deptName;

private List<Employee> list;

public List<Employee> getList() {
return list;
}
public void setList(List<Employee> list) {
this.list = list;
}
......
}

 

創建DepartmentMapper接口文件,並添加以下方法:
xml

public Department getDeptByIdPlus(Integer id);

 


2.sql映射文件中的內容爲:【collection:嵌套結果集的方式:使用collection標籤訂義關聯的集合類型元素的封裝規則】

<!-- public Department getDeptByIdPlus(Integer id); -->
<resultMap type="com.neuedu.entity.Department" id="getDeptByIdPlusMap">
  <id column="did" property="id"/>
  <result column="dept_name" property="deptName"/>
  <!-- 
    collection:定義關聯集合類型的屬性的封裝規則
    ofType:指定集合裏面元素的類型
  -->
  <collection property="list" ofType="com.neuedu.entity.Employee">
  <!-- 定義這個集合中元素的封裝規則 -->
    <id column="eid" property="id"/>
    <result column="user_name" property="userName"/>
    <result column="email" property="email"/>
    <result column="gender" property="gender"/>
  </collection>
</resultMap>

<select id="getDeptByIdPlus" resultMap="getDeptByIdPlusMap">
  SELECT d.`id` did, d.`dept_name` dept_name,e.`id` eid,e.`user_name` user_name,e.`email` email,e.`gender` gender
  FROM `tbl_dept` d
  LEFT JOIN tbl_employee e
  ON e.`d_id` = d.`id` 
  WHERE d.`id` = #{id}
</select>

 

 

3.測試方法爲:

@Test
public void testGetEmployee(){
  DepartmentMapper mapper = openSession.getMapper(DepartmentMapper.class);
  Department department = mapper.getDeptByIdPlus(2);
  System.out.println(department);
}

  

第二種:使用分步查詢結果集的方式:

1.若是使用分步查詢的話,咱們的sql語句就應該爲:

SELECT * FROM `tbl_dept` WHERE id = 2;
SELECT * FROM `tbl_employee` WHERE d_id = 2;

 


2.在DepartmentMapper接口文件中添加方法,以下所示:

public Department getDeptWithStep(Integer id);

 

 

3.再從EmployeeMapper接口中添加一個方法,以下所示:

public List<Employee> getEmployeeByDeptId(Integer deptId);

 


並在響應的sql映射文件中添加相應的sql語句對象

<select id="getEmployeeByDeptId" resultType="com.neuedu.entity.Employee">
  select * from tbl_employee where d_id = #{departId}
</select>  


4.在DepartmentMapper映射文件中:

<resultMap type="com.neuedu.entity.Department" id="getDeptWithStepMap">
  <id column="id" property="id"/>
  <result column="dept_name" property="deptName"/>
  <collection property="list" select="com.neuedu.mapper.EmployeeMapper.getEmployeeByDeptId" column="id"></collection>
</resultMap>
<select id="getDeptWithStep" resultMap="getDeptWithStepMap">
  SELECT id ,dept_name FROM tbl_dept WHERE id = #{id}
</select>

 


5.測試類:

@Test
public void testGetEmployee(){
  DepartmentMapper mapper = openSession.getMapper(DepartmentMapper.class);
  Department department = mapper.getDeptWithStep(2);
  System.out.println(department);
}

  


6.總結:

映射(一)對多、(多)對多的關聯關係=======》【映射"對多"的關聯關係】
1.必須使用collection節點進行映射
2.基本示例:
注意:1). ofType指定集合中的元素類型
2).collection標籤
映射多的一端的關聯關係,使用ofType指定集合中的元素類型
              columnprefix:指定列的前綴
使用情境:若關聯的數據表和以前的數據表有相同的列名,此時就須要給關聯的列其"別名".
如有多個列須要起別名,能夠爲全部關聯的數據表的列都加上相同的前綴,而後再映射時指定前綴。

blog

相關文章
相關標籤/搜索