上一篇文章:《Mybatis基本知识六:多参数接收问题》
若文中有纰漏,请多多指正!!!
1. 前言
当查询的结果涉及多张具有关联关系的表时,就需要进行关联关系查询。根据表和表之间的关联关系的不同,关联关系查询大致分为以下几类:一对多关联查询
一对一关联查询
多对多关联查询
多对一关联查询
这里的关联查询是指:在查询一方的时候,同时将关联的另一方的信息也查询出来。
本节主要分析【一对多关联查询】,其他关联查询,在后续章节中分析。
2. 一对多关联查询
一对多关联查询:是指在查询一的一方的时候会将其所关联的多的一方的数据也查询出来。 一对多关联查询在mapper配置查询时又可以大致分两种配置写法:多表连接查询
多表单独查询
下面的示例中将以表Country(国家)和表Provice(区域)举例说明一对多关联查询的应用:一个国家可以有多个区域划分。1) 数据定义(MySql)
/**国家*/
create table Country(
id int primary key auto_increment comment '主键',
cname varchar(50) comment '名称'
);
INSERT INTO `country` VALUES (1, '北京');
INSERT INTO `country` VALUES (2, '天津');
/**地区*/
create table Provice(
id int primary key auto_increment comment "主键",
pname varchar(50) comment "名称",
cid int comment "Country主键Id"
);
INSERT INTO `provice` VALUES (1, '红桥区', 2);
INSERT INTO `provice` VALUES (2, '北辰区', 2);
INSERT INTO `provice` VALUES (3, '海淀区', 1);
INSERT INTO `provice` VALUES (4, '朝阳区', 1);2) 实体类定义
需要注意如果实体类定义的是双向关联时,即在实体类中都将对方作为域属性出现,那么toStirng()方法定义时要引起高度注意,不要让toString()方法都可以输出对方的信息,避免出现循环递归调用,程序异常。为避免这种情况,我们只让主查询的一方输出关联的信息即可。
/**
* 国家
* @author Administrator
* @description 一的一方
*/
public class Country {
private Integer id;//主键
private String cname;//名称
private List provices;//省份
//setter and getter and toString
}
/**
* 区域
* @author Administrator
* @description 多的一方
*/
public class Provice {
private Integer id;
private String pname;//名称
private Integer cid;//Country主键Id
//setter and getter and toString
}3)接口定义
/**
* 一对多查询
*/
public interface CountryDao {
/**
* 根据Country主键查询该国家下的所有区域
* 多表单独查询
*/
Country findCountryByIdSingle(Integer id);
/**
* 根据Country主键查询该国家下的所有区域
* 多表连接查询
*/
Country findCountryByIdGather(Integer id);
}4)测试定义
public class TestDemo {
private CountryDao dao;
private SqlSession sqlsession;
@Before
public void setUp() throws Exception{
sqlsession = MyBatisUtil.getSqlSession();
dao = sqlsession.getMapper(CountryDao.class);
}
/**
* 一对多查询:
* 在查询一方对象数据的时候,同时将其关联的多方对象的数据也都关联查询出来。
*/
@Test
public void findCountry(){
//1.多表单独查询
Country single = dao.findCountryByIdSingle(1);
System.out.println(single);
//2.多表连接查询
Country gather = dao.findCountryByIdGather(2);
System.out.println(gather);
}
@After
public void setDown(){
//关闭资源
if(sqlsession != null){
sqlsession.close();
}
}
}5)多表单独查询
多表单独查询是指多张表根据关联字段各自查询出各自的相关内容,最后将主表的查询结果联合其他表的查询结果,封装成一个对象去返回。
注意:如果查询是跨映射文件的,那么在查询使用的id时一定要加上其对应映射文件的namespace。mapper配置
select * from country where id = #{id}
select="selectProviceByCid" column="id"/>
select * from provice where cid = #{id}
测试结果
Country [id=1, cname=北京, provices=[Provice [id=3, pname=海淀区, cid=1], Provice [id=4, pname=朝阳区, cid=1]]]6)多表连接查询
多表连接查询是指多张表根据关联字段组成一张表的形式进行查询。mapper配置
select c.id counid,c.cname,p.id pid,p.pname,p.cid from country c,provice p
where c.id = p.cid and c.id = #{id}
测试结果
Country [id=2, cname=天津, provices=[Provice [id=1, pname=红桥区, cid=2], Provice [id=2, pname=北辰区, cid=2]]]7)练习源码地址
链接:https://pan.baidu.com/s/1kkVnkE9rjwjGcLeHgJ1gdg
提取码:gorf