欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

MyBatis多表連接查詢的實例教程

 更新時間:2020年12月09日 15:33:36   作者:csdn_小東  
這篇文章主要給大家介紹了關于MyBatis多表連接查詢的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

多表連接的兩種方式(數據庫邏輯模型):

1.一對一關系

2.一對多關系

一、通過 resultMap 和 association 實現一對一關系

在 mapper.xml 文件里面的代碼:

 <resultMap type="com.pojo.TRecruitment" id="tRecruitmentCollegeResultMap">
	<id property="id" column="id" />
	<result property="title" column="title" />
	<result property="litimg" column="litimg" />
	<result property="publishedTime" column="published_time" />
	<result property="author" column="author" />
	<result property="collegeId" column="college_id" />
	<result property="type" column="type" />
	<result property="details" column="details" />
	
	<!-- association :配置一對一屬性 -->
	<!-- property:實體類中里面的 TCollege 屬性名 -->
	<!-- javaType:屬性類型 -->
	<association property="tCollege" javaType="com.pojo.TCollege" >
		<!-- id:聲明主鍵,表示 college_id 是關聯(lián)查詢對象的唯一標識-->
		<id property="collegeId" column="college_id" />
		<result property="collegeName" column="college_name" />
		<result property="collegeImg" column="college_img" />
	</association>
</resultMap>
 
<!-- 一對一關聯(lián),查詢訂單,訂單內部包含用戶屬性 -->
<select id="querytTRecruitmentResultMap" resultMap="tRecruitmentCollegeResultMap">
	SELECT
	r.id,
	r.title,
	r.litimg,
	r.published_time,
	r.author,
	r.type,
	r.details,
	c.college_name
	FROM
	`t_recruitment` r
	LEFT JOIN `t_college` c ON r.college_id = c.college_id
</select>

在 mapper.java 文件里面寫接口:

List<TRecruitment> querytTRecruitmentResultMap();

在對應的實體類中聲明另外一個實體類:

二、通過 resultMap 和 collection 實現一對多關系

xml 文件:

<!-- 一個用戶,擁有多個訂單 -->
<resultMap type="User" id="UserAndOrdersResultMap">
 
	<!-- 先配置 User 的屬性 -->
	<id column="id" property="id" />
	<result column="username" property="username" />
	<result column="birthday" property="birthday" />
	<result column="sex" property="sex" />
	<result column="address" property="address" />
 
	<!-- 再配置 Orders 集合 -->
	<collection property="ordersList" ofType="Orders">
		<id column="oid" property="id" />
		<result column="user_id" property="userId" />
		<result column="number" property="number" />
		<result column="createtime" property="createtime" />
	</collection>
 
</resultMap>
 
<select id="findUserAndOrders" resultMap="UserAndOrdersResultMap">
	SELECT u.*, o.`id` oid, o.`number`, o.`createtime`
	FROM USER u, orders o
	WHERE u.`id` = o.`user_id`;
</select>

總結

到此這篇關于MyBatis多表連接查詢的文章就介紹到這了,更多相關MyBatis多表連接查詢內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論