Mybatis学习(9)多表之多对一关联查询

本文通过国家与部长的实例,详细介绍了在MyBatis中实现多对一查询的具体步骤,包括实体定义、数据库设计、接口声明、测试类编写及映射文件配置,并附带完整代码。

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

上篇博客学习了一对多查询,这次看多对一。这次同样适用国家和部长的例子,由于实体,数据库一样。这里直接给出代码。还是先给出项目结构图

1、定义实体

 

2、定义数据库

国家表:country

部长表:minister

 

3、定义接口

public interface IMinisterDao {
	Minister selectMinisterById(int id);
}

4、定义测试类

public class MyTest {
		
	private IMinisterDao dao ;
	private SqlSession sqlSession;
	
	@Before
	public void testBefore(){
		sqlSession = MybatisUtil.getSqlSession();
		dao = sqlSession.getMapper(IMinisterDao.class);
	}
	
	@After
	public void after(){
		if(sqlSession!=null){
			sqlSession.close();
		}
	}
	
	
	@Test
	public void testSelectMinisterById() {
		Minister minister=dao.selectMinisterById(1);
		System.out.println(minister);
	}
	
	
}

 

5、定义映射文件

A:多表链接查询

B:多表单独查询

<?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.test.dao.IMinisterDao">
	
	<select id="selectCountryById" resultType="Country">
		select cid,cname from country where cid=#{ooo}
	</select>
	
	<resultMap type="Minister" id="ministerMapper">
		<id column="mid" property="mid"/>
		<result column="mname" property="mname"/>
		<association property="country" 
				     javaType="Country"
				     select="selectCountryById"
				     column="countryid"/>
	</resultMap>
	
	<select id="selectMinisterById" resultMap="ministerMapper">
		select mid,mname,countryid from minister where mid=#{xxx}
	</select>
	
</mapper>

6、其他类

其他类的代码,在上一篇博客里面。

附上源码地址:https://download.youkuaiyun.com/download/sdddlll/10859871

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值