Mybatis下的数据库表自关联查询

本文通过一个具体的例子展示了如何在Mybatis中进行数据库表的自关联查询,涉及MySQL创建自关联表prentice,以及通过pid获取师傅和所有徒弟信息的操作。虽然实体类和查询代码未详述,但测试类表明了查询功能的实现。

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

简单粗暴点,直接上代码吧

mysql创建一张表,表名prentice

表中林朝英有两个徒弟,分别是小龙女和李莫愁。而小龙女有徒弟杨过,李莫愁有徒弟洪凌波。 

现在需要通过pid查询出师傅所收的全部徒弟信息。


1. 创建 Prentice实体类 (略)


2. 创建PrenticeMapper接口

package com.wl.mapper;

import java.util.List;

import com.wl.pojo.Prentice;

//根据pid查询徒弟信息
public interface PrenticeMapper {
	List<Prentice> selectPrenticeByPid(int pid);
}


3. 配置PrenticeMapper.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 查询师傅所带的徒弟 -->
<mapper namespace="com.wl.mapper.PrenticeMapper">
	
	<resultMap type="Prentice" id="prenticeMapper">
		<id column="id" property="id"/>
		<result column="name" property="name"/>
		<collection property="prentices" 
					ofType="Prentice"
					select="selectPrenticeByPid"
					column="id"/>
	</resultMap>
	
	<select id="selectPrenticeByPid" resultMap="prenticeMapper">
		select id,name from prentice where pid=#{pid}
	</select>
	 
</mapper>

4.  工具类MybatisUtil及mybatis.xml 文件的配置此处就略写啦,相信大家都能搞定。下面就直接上测试

5. 测试类

public class TestPrentice {
	
	private PrenticeMapper mapper;
	private SqlSession sqlSession;
	
	@Before
	public void Before(){
		sqlSession = MyBatisUtil.getSqlSession();
		mapper = sqlSession.getMapper(PrenticeMapper.class);
	}
	@After
	public void After(){
		if(sqlSession!= null){
			sqlSession.close();
		}
	}
	
	@Test
	public void selectPrenticeByPid(){
		List<Prentice> prentices = mapper.selectPrenticeByPid(1);
		for (Prentice prentice : prentices) {
			System.out.println(prentice);
		}
	}
}


经测试,小龙女及其徒弟杨过,李莫愁及其徒弟洪凌波都被打印在控制台~~~

关于查询师傅及其徒弟的信息,在此就不贴出来啦~~~

不足之处,欢迎指正!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值