Mybatis 一对多关联查询的两种方式:嵌套结果与嵌套查询

本文详细介绍了MyBatis中嵌套查询的使用方法,包括如何通过Mapper接口和XML配置实现嵌套结果和嵌套查询,展示了如何将查询结果映射到自定义的Java对象中,以及如何处理一对多的关系。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

嵌套结果

Mapper 接口

List<TUser> selectUserJobs1();

返回结果会将查出来的表根据<id>合并

Mapper XML配置

<resultMap id="BaseResultMap" type="TUser">	
	<id column="id" property="id" />
		<result column="userName" property="userName" />
	<result column="realName" property="realName" />
	<result column="sex" property="sex" />
	<result column="mobile" property="mobile" />
	<result column="email" property="email" />
	<result column="note" property="note" />
</resultMap>
<resultMap id="userAndJobs1" extends="BaseResultMap" type="TUser">
	<collection property="jobs"
		ofType="com.enjoylearning.mybatis.entity.TJobHistory" >
		<result column="comp_name" property="compName" jdbcType="VARCHAR" />
		<result column="years" property="years" jdbcType="INTEGER" />
		<result column="title" property="title" jdbcType="VARCHAR" />
	</collection>
</resultMap>
<select id="selectUserJobs1" resultMap="userAndJobs1">
	select
	a.id,
	a.userName,
	a.realName,
	a.sex,
	a.mobile,
	b.comp_name,
	b.years,
	b.title
	from t_user a,
	t_job_history b
	where a.id = b.user_id
</select>

TUser 对象

@Data
public class TUser{
	
    private Integer id;

    private String userName;

    private String realName;

    private Byte sex;

    private String mobile;
	
    private String email;

    private String note;
    //一对多的体现
    private List<TJobHistory> jobs ;
}

嵌套查询

Mapper 接口

List<TUser> selectUserJobs2();

Mapper XML配置

<resultMap id="userAndJobs2" extends="BaseResultMap" type="TUser">
	<collection property="jobs" fetchType="lazy" column="id"
		select="com.enjoylearning.mybatis.mapper.TJobHistoryMapper.selectByUserId" />
</resultMap>
<select id="selectUserJobs2" resultMap="userAndJobs2">
	select
	a.id,
	a.userName,
	a.realName,
	a.sex,
	a.mobile
	from t_user a
</select>

这种方式会把所有的 TUser 查出来,t_user 有多少条,就会查出多少条

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值