1. 程式人生 > >Mybatis一對一、一對多關聯對映

Mybatis一對一、一對多關聯對映

這裡拿學生和班級比喻:

一個班級有多個學生,這裡是一對多。

學生所在的班級,是多對一,其實可以理解為一對一。

1、一對多

Student類:

public class Students {

	private Integer id;
	private String name;
	private Clazz clazz;
	
	//getter setter
}

Clazz類:

public class Clazz {

	private Integer id;
	private String name;
	private List<Students> students;
	
	//getter setter
}

下面配置Mapper.xml檔案:要實現一對多關聯查詢,有兩種方式:

  • 巢狀結果: 使用巢狀結果對映來處理重複的聯合結果的子集
  • 巢狀查詢:通過執行另外一個SQL 對映語句來返回預期的複雜型別

巢狀結果:

<?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.thr.dao.ClazzDao">  
	
	<!-- 一對多的第一種寫法,一般考慮到效能問題,不會這麼實現 -->
	<resultMap type="Clazz" id="ClazzMap">
		<id column="id" property="id"/>
		<result column="name" property="name"/>
		<collection property="students" ofType="Students" column="id">
			<id column="sid" property="id"/><!-- 這裡的column對應的是下面查詢的別名,而不是表字段名 -->
			<result column="sname" property="name"/><!-- property對應JavaBean中的屬性名 -->
		</collection>
	</resultMap>
	
	
	<!-- 查詢所有的班級的所有學生 -->
	<select id="getClazzWithStudent" parameterType="Clazz" resultMap="ClazzMap">
		SELECT
			c.id,
			c.name,
			s.id AS sid,
			s. name AS sname
		FROM
			clazz c
		LEFT JOIN students s ON c.id = s.clazz_id
	</select>
</mapper>

 

這裡使用collection標籤,collection用於一對多的關聯查詢

property-物件的屬性名稱(對應javabean裡面的)

ofType-表示集合當中的型別

column-對應的該表的資料庫主鍵欄位

巢狀查詢:

<!-- 一對多的第二種寫法 -->
	<resultMap type="Clazz" id="ClazzMaps">
		<id column="id" property="id"/>
		<result column="name" property="name"/>
		<collection property="students" ofType="Students" select="getStudentsById" column="id">
		</collection>
	</resultMap>
	
	
	<!-- 查詢所有的班級下的所有學生 -->
	<select id="getAllClazz" parameterType="Clazz" resultMap="ClazzMaps">
		SELECT
			*
		FROM
			clazz
	</select>

2、一對一

一對一也有兩種同樣的方法,下面只寫一種:

<!--巢狀查詢  -->
<resultMap type="Students" id="StudentsMap">
    <id property="id" column="id" />
    <result property="name" column="name" />
    <association property="clazz" column="clazz_id" javaType="Clazz" select="getClazzById">
    </association>
</resultMap>

<!-- 使用了sql別名  -->
<select id="getStudent" parameterType="int" resultType="Students">
    SELECT * FROM students WHERE t_id=#{id}
</select>

注意:association中的column的值是對應到所查詢到資料庫表的外來鍵的,很多人多搞不清。