在关系数据库的多表关系中分为三种关联关系:一对一,一对多,多对多
一对一:在任意一方引入对方主键最为外键
一对多:最多的一方,添加“一”的一方的主键作为外键
多对多:产生中间关系表,引入两张表的主键作为外键,两个主键称为联合主键或使用新的字段作为主键
在< resultMap>元素中有一个< association>子元素,MyBatis就是通过钙元素来处理一对一关联关系的。
在< associate>元素中,通常可以配置以下属性。
1.property:指定映射到的实体类对象属性,与表字段一一对应
2.column:指定表中国对应的字段
3.javaType:指定映射到实体对象属性的类型
4.select:指定引入嵌套查询的子SQL御酒,该属性用于关联映射中的嵌套查询。
5.fetchType:指定在关联查询时是否启用延迟加载,fetchType属性有lazy和eager两个属性值,默认值为lazy(默认关联映射延迟加载)
< associate>示例
示例:
(1)创建在mybatis下创建两个表,名为tb_idcard和tb_person,并向其中输入一些数据
create table tb_idcard(id int PRIMARY KEY AUTO_INCREMENT,CODE VARCHAR(18));
insert INTO tb_idcard(CODE) VALUES('152221192711020624');
insert INTO tb_idcard(CODE) VALUES('152201199008150317');
create table tb_person(id int primary key auto_increment,name varchar(32),age int,sex varchar(8),card_id int unique,foreign key(card_id) references tb_idcard(id));
insert into tb_person(name,age,sex,card_id) values('Rose',29,'女',1);
insert into tb_person(name,age,sex,card_id) values('tom',27,'男',2);
(2)创建一个名为guanlian的Web项目,并向其导入相应的JAR包,log4j日志文件、MyBatis工具类一节mybatis-config.xml核心配置文件
(3)在项目下的com.itheima.po包下创建两个持久化类IdCard类和Person
IdCard
package com.itheima.po;
public class IdCard {
private Integer id;
private String code;
public Integer getId(){
return id;
}
public void setId(Integer id){
this.id=id;
}
public String getCode(){
return code;
}
public void setCode(String code){
this.code=code;
}
public String toString(){
return "IdCard[="+id+",code="+code+"]";
}
}
Person
package com.itheima.po;
public class Person {
private Integer id;
private String name;
private Integer age;
private String sex;
private IdCard card;
public Integer getId(){
return id;
}
public void setId(Integer id){
this.id=id;
}
public String getUsername(){
return name;
}
public void setuserName(String name){
this.name=name;
}
public void setAge(Integer age){
this.age=age;
}
public Integer getAge(){
return age;
}
public String getSex(){
return sex;
}
public void setSex(String sex){
this.sex=sex;
}
public IdCard getCard(){
return card;
}
public void setCard(IdCard card){
this.card=card;
}
public String toString(){
return "Person[id="+id+",name="+name+",age="+age+",Sex="+sex+",card="+card+"]";
}
}
(4)在com.itheima.mapper包下创建IdCardMapper.xml和PersonMapper.xml
IdCardMapper.xml
PersonMapper.xml
(5)修改mybatis-config.xml配置文件
(6)在com.itheima.test包下创建一个测试类
package com.itheima.test;
import java.io.IOException;
import com.itheima.utils.*;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.*;
import org.junit.Test;
import com.itheima.po.*;
public class MybatisAssociatedTest {
@Test
public void findPersonByIdTest(){
SqlSession session=MybatisUtils.getSession();
Person person=session.selectOne("com.itheima.mapper."+"PersonMapper.findPersonById",1);
System.out.println(person);
session.close();
}
}
上面的MyBatis嵌套查询的方式要执行多条SQL语句,这对于大型数据集合和队列不是很好。
我们可以采用MyBatis提供的嵌套结果方式,进行关联查询。
在PersonMapper.xml中,使用MyBatis嵌套结果的方式。
MyBatis中有一个< resultMap>元素,其中包含了一个< collection>子元素,MyBatis通过这个子元素来处理一对多联系。< collection>子元素的属性大部分与< association>元素相同,其中包含了一个特殊元素——ofType,ofType与javaType对应,用于指定实体对象中集合类属性所包含的元素类型。
< collection>元素的示例配置
示例:
(1)创建两个数据库表tb_user和tb_orders,并向其中导入一些数据
create table tb_user(id int(22) PRIMARY KEY AUTO_INCREMENT,username varchar(22),address varchar(256));
insert into tb_user values('1','詹姆斯','克利夫兰');
insert into tb_user values('2','科比','洛杉矶');
insert into tb_user values('3','保罗','洛杉矶');
create table tb_orders(id int(32) PRIMARY KEY AUTO_INCREMENT,number varchar(32) not null,user_id int(32) not null,FOREIGN KEY(user_id) REFERENCES tb_user(id));
insert into tb_orders values('1','1000011','1');
insert into tb_orders values('2','1000012','1');
insert into tb_orders values('3','1000013','2');
(2)在com.itheima.po包中创建持久类Orders和User
Orders
package com.itheima.po;
public class Orders {
private Integer id;
private String number;
public Integer getId(){
return id;
}
public void setId(Integer id){
this.id=id;
}
public String getNumber(){
return number;
}
public void setNumber(String number){
this.number=number;
}
public String toString(){
return "Orders[id="+id+",number="+number+"]";
}
}
Users
package com.itheima.po;
import java.util.List;
public class User {
private Integer id;
private String username;
private String address;
private List ordersList;
public Integer getId(){
return id;
}
public void setId(Integer id){
this.id=id;
}
public String getUsername(){
return username;
}
public void setuserName(String username){
this.username=username;
}
public String getAddress(){
return address;
}
public void setAddress(String address){
this.address=address;
}
public List getOrdersList(){
return ordersList;
}
public void setOrdersList(List ordersList){
this.ordersList=ordersList;
}
public String toString(){
return "[id="+id+",username="+username+",address="+address+"ordersList="+ordersList+"]";
}
}
(3)在com.itheima.mapper包下创建UserMapper.xml
(4)在mybatis-config.xml中导入UserMapper.xml
(5)编写测试类
@Test
public void findUserTest(){
SqlSession session=MybatisUtils.getSession();
User user=session.selectOne("com.itheima.mapper."+"UserMapper.findUserWithOrders",1);
System.out.println(user);
session.close();
}
多对多的关联关系通常使用一个中间表来维护。例如:中间表的id作为外键参照订单表的id,商品id作为外键参照商品表的id。
示例:
(1)创建商品表和中间表
create table tb_product(
id int(32) primary key auto_increment,
name varchar(32),
price double
);
insert into tb_product values('1','Java基础入门','44.5');
insert into tb_product values('2','Java Web程序开发入门','38.5');
insert into tb_product values('3','SSM框架整合实战','50');
create table tb_ordersitem(
id int(32) primary key auto_increment,
orders_id int(32),
product_id int(32),
foreign key(orders_id) references tb_orders(id),
foreign key(product_id) references tb_product(id)
);
insert into tb_ordersitem values('1','1','1');
insert into tb_ordersitem values('2','1','3');
insert into tb_ordersitem values('3','3','3');
(2)在com.itheima.po包中创建持久类Product并在类中定义相关属性和方法
package com.itheima.po;
import java.util.List;
public class Product {
private Integer id;
private String name;
private Double price;
private List orders;
public Integer getId(){
return id;
}
public void setId(Integer id){
this.id=id;
}
public String getname(){
return name;
}
public void setName(String name){
this.name=name;
}
public Double getPirce(){
return price;
}
public void setPirce(Double price){
this.price=price;
}
public List getOrders(){
return orders;
}
public void setOrders(List orders){
this.orders=orders;
}
public String toString(){
return "Product[id="+id+",name="+name+",price="+price+",orders="+orders;
}
}
创建持久化类Order
package com.itheima.po;
import java.util.List;
public class Orders {
private Integer id;
private String number;
private List productList;
public Integer getId(){
return id;
}
public void setId(Integer id){
this.id=id;
}
public String getNumber(){
return number;
}
public void setNumber(String number){
this.number=number;
}
public List getProductList(){
return productList;
}
public void setProductorList(List productList){
this.productList=productList;
}
public String toString(){
return "Orders[id="+id+",number="+number+",productList="+productList+"]";
}
}
(3)在com.itheima.mapper包中,创建订单实体映射文件OrderMapper.xml和商品实体映射文件ProductMapper.xml。
OrderMapper.xml
ProductorMapper
(4)导入到mybatis-config.xml中
(5)在测试类中添加测试方法
@Test
public void findOrderTest(){
SqlSession session=MybatisUtils.getSession();
Orders orders=session.selectOne("com.itheima.mapper."+"OrderMapper.findOrdersWithProduct",1);
System.out.println(orders);
session.close();
}