温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

在MyBatis中实现多表连接查询的方法

发布时间:2020-12-10 15:44:05 来源:亿速云 阅读:1515 作者:Leah 栏目:开发技术

这篇文章将为大家详细讲解有关在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 是关联查询对象的唯一标识-->
		<id property="collegeId" column="college_id" />
		<result property="collegeName" column="college_name" />
		<result property="collegeImg" column="college_img" />
	</association>
</resultMap>
 
<!-- 一对一关联,查询订单,订单内部包含用户属性 -->
<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();

在对应的实体类中声明另外一个实体类:

在MyBatis中实现多表连接查询的方法

二、通过 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中实现多表连接查询的方法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI