MyBatis学习笔记(二)之关联关系

jerry Java 2016年03月10日 收藏

今天主要学习的关联关系是一对一关系与一对多关系。

一、一对一关系

还是通过例子来解释说明。(一个妻子对应一个丈夫)。

1)数据库信息

create table t_wife(
id int primary key auto_increment,
wife_name varchar(),
fk_husband_id int
);
create table t_husband(
id int primary key auto_increment,
husband_name varchar()
);
insert into t_husband values (null,'hello');
insert into t_wife values(null,'kitty',) 

2)对应的JavaBean代码

虽然在数据库里只有一方配置的外键,但是这个一对一是双向的关系。

HusbandBean.java

package com.cy.mybatis.beans;
import java.io.Serializable;
/**
* one to one
* @author acer
*
*/
public class HusbandBean implements Serializable{
private static final long serialVersionUID = L;
private Integer id;
private String name;
private WifeBean wife;
public HusbandBean() {
super();
}
public HusbandBean(Integer id, String name, WifeBean wife) {
super();
this.id = id;
this.name = name;
this.wife = wife;
}
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 WifeBean getWife() {
return wife;
}
public void setWife(WifeBean wife) {
this.wife = wife;
}
@Override
public String toString() {
return "Husband [id=" + id + ", name=" + name + ", wife=" + wife + "]";
}
}

WifeBean.java

package com.cy.mybatis.beans;
import java.io.Serializable;
/**
* one to one
* @author acer
*
*/
public class WifeBean implements Serializable{
private static final long serialVersionUID = L;
private Integer id;
private String name;
private HusbandBean husband;
public WifeBean() {
super();
}
public WifeBean(Integer id, String name, HusbandBean husband) {
super();
this.id = id;
this.name = name;
this.husband = husband;
}
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 HusbandBean getHusband() {
return husband;
}
public void setHusband(HusbandBean husband) {
this.husband = husband;
}
@Override
public String toString() {
return "Wife [id=" + id + ", name=" + name + ", husband=" + husband
+ "]";
}
} 

3)接下来建立两个接口,HusbandMapper,WifeMapper.

HusbandMapper

package com.cy.mybatis.mapper;
import com.cy.mybatis.beans.HusbandBean;
public interface HusbandMapper {
/**
* 根据id查询丈夫信息
* @param id
* @return
* @throws Exception
*/
public HusbandBean selectHusbandById (int id) throws Exception;
/**
* 根据id查询丈夫与妻子信息
* @param id
* @return
* @throws Exception
*/
public HusbandBean selectHusbandAndWife(int id) throws Exception;
} 

4)定义HusbandMapper.xml文件

<?xml version="." encoding="UTF-"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper ." "http://mybatis.org/dtd/mybatis--mapper.dtd">
<mapper namespace="com.cy.mybatis.mapper.HusbandMapper">
<resultMap type="HusbandBean" id="husbandAndWife">
<id property="id" column="id" javaType="java.lang.Integer"/>
<result property="name" column="name" javaType="java.lang.String"/>
<!-- association