欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

MyBatis多表连接查询的实例教程

时间:2022-05-17 09:25:26|栏目:JAVA代码|点击:

多表连接的两种方式(数据库逻辑模型):

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();

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

二、通过 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>

总结

上一篇:java+selenium 网易云音乐刷累计听歌数的方法

栏    目:JAVA代码

下一篇:Java C++解决在排序数组中查找数字出现次数问题

本文标题:MyBatis多表连接查询的实例教程

本文地址:http://www.codeinn.net/misctech/202088.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有