我現在有兩張表,一張丈夫表,一張妻子表,每個丈夫和妻子是一一對應的關係
SQL如下,我要找出id爲1的丈夫及其妻子的信息
SELECT * from husband hus, wife wife WHERE hus.wife_id = wife.wife_id
and hus.wife_id=1
因爲丈夫和妻子之間存在一一對應的關係,所以我丈夫的Javabean設計如下:
public class Husband {
private Long husId;
private String husName;
private Integer husAge;
private Long wifeId;
private Wife wife;
public Long getHusId() {
return husId;
}
public void setHusId(Long husId) {
this.husId = husId;
}
public String getHusName() {
return husName;
}
public void setHusName(String husName) {
this.husName = husName;
}
public Integer getHusAge() {
return husAge;
}
public void setHusAge(Integer husAge) {
this.husAge = husAge;
}
public Long getWifeId() {
return wifeId;
}
public void setWifeId(Long wifeId) {
this.wifeId = wifeId;
}
public Wife getWife() {
return wife;
}
public void setWife(Wife wife) {
this.wife = wife;
}
@Override
public String toString() {
return "Husband [husId=" + husId + ", husName=" + husName + ", husAge=" + husAge + ", wifeId=" + wifeId
+ ", wife=" + wife + "]";
}
}
可以 看到,丈夫的實體類中包含着妻子信息Wife這個實體類,那麼這時候使用,你想通過mybatis查詢出包含妻子信息的完整實體類,就需要藉助resultMap了,具體的看下面的xml
<?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="dao.HusDaoImpl">
<resultMap type="bean.Husband" id="hus">
<result property="husId" javaType="java.lang.Long" column="hus_id"/>
<result property="husName" javaType="java.lang.String" column="hus_name"/>
<result property="husAge" javaType="java.lang.Integer" column="hus_age"/>
<result property="wifeId" javaType="java.lang.Long" column="wife_id"/>
<association property="wife">
<result property="wifeId" javaType="java.lang.Long" column="wife_id"/>
<result property="wifeName" javaType="java.lang.String" column="wife_name"/>
<result property="wifeAge" javaType="java.lang.Integer" column="wife_age"/>
</association>
</resultMap>
<select id="select" parameterType="java.lang.Long" resultMap="hus">
SELECT * from husband hus, wife wife WHERE hus.wife_id = wife.wife_id
and hus.wife_id=#{0}
</select>
</mapper>
可以看到,husband這個類中的wife信息就是藉助 association標籤來說明清楚哪些字段對應哪些值