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

 

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

 

 

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

 

 

 

 

 

原文:https://blog.csdn.net/weidong_y/article/details/80557941

 

转载于:https://www.cnblogs.com/panchanggui/p/10872506.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值