关联关系概述
在关系数据库的多表关系中分为三种关联关系:一对一,一对多,多对多
一对一:在任意一方引入对方主键最为外键
一对多:最多的一方,添加“一”的一方的主键作为外键
多对多:产生中间关系表,引入两张表的主键作为外键,两个主键称为联合主键或使用新的字段作为主键
一对一
在< resultMap>元素中有一个< association>子元素,MyBatis就是通过钙元素来处理一对一关联关系的。
在< associate>元素中,通常可以配置以下属性。
1.property:指定映射到的实体类对象属性,与表字段一一对应
2.column:指定表中国对应的字段
3.javaType:指定映射到实体对象属性的类型
4.select:指定引入嵌套查询的子SQL御酒,该属性用于关联映射中的嵌套查询。
5.fetchType:指定在关联查询时是否启用延迟加载,fetchType属性有lazy和eager两个属性值,默认值为lazy(默认关联映射延迟加载)
< associate>示例
<association property="card" column="card_id" javaType="com.itheima.po.IdCard"
select="com.itheima.mapper.IdCardMapper.findCodeById"/>
<association property="card" javaType="com.itheima.po.IdCard">
<id property="id" column="card_id"/>
<result property="code" column="code"/>
</association>
示例:
(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</