方法一:使用collection實現一對多映射
在用到collection的時候是因爲要應對一對多的情況,數據結構是一對多。
比如要查某個家庭的父親和他的所有兒女的信息
如下所示是Father對象
/**
* 這相當於父類,
* son是它兒子,
* 它有好幾個兒子,
* 所有用list集合裝起來
*/
@SuppressWarnings("serial")//該註釋用於去除Serializable產生的黃色警告
public class Father extends Serializable {
private long id;
private int age;//年齡
private String name;//名稱
private String identity;//身份證號碼
private List<Son> sonList;//兒子表參數集合
// 以下省略set\get方法。。。。
public List<Son> getSonList() {
return sonList;
}
public void setSonList(List<Son> sonList) {
this.sonList = sonList;
}
}
如下所示是Son對象
/**
* 這是son是,Father是它父親,
* 這是它的具體屬性
*/
@SuppressWarnings("serial")//該註釋用於去除Serializable產生的黃色警告
public class Son extends Serializable {
private long id;
private int age;//年齡
private String name;//名稱
private String identity;//身份證號碼
private String fatherId;//父ID
// 以下省略set\get方法。。。。
}
接下來就是xml中的東西了,相關SQL語句的書寫,這是和Dao映射的xml文件,比如文件名爲 fatherDao.xml
<resultMap id="sonMap" type="com.test.model.Son">
<id column="id" property="id"/>
<result column="age" property="age"/>
<result column="name" property="name"/>
<result column="identity" property="identity"/>
<result column="father_id" property="fatherId"/>
<result column="extend" property="extend"/>
</resultMap>
<select id="selectSon" resultMap="sonMap">
SELECT
son.id as id,
son.age as age,
son.name as name,
son.identity as identity,
son.father_id as father_id
FROM
t_son son
WHERE
son.father_id = #{fatherId}
ORDER BY
son.age ASC
</select>
<resultMap id="fatherSonMap" type="com.test.model.Father">
<id column="id" property="id"/>
<result column="age" property="age"/>
<result column="name" property="name"/>
<result column="identity" property="identity"/>
<collection property="sonList" column="id" ofType="com.test.model.Son" javaType="java.util.List" select="selectSon"/>
</resultMap>
<!-- 此處解釋一下參數
property參數後面跟的是Father中對應的參數名稱
column參數後面跟的是要傳遞到selectSon的SQL語句中的參數(此參數是本條語句中的id參數)
ofType參數後面跟的是對應的Son對象
javaType後跟的是返回的結果參數類型
select後面跟的是要執行的SQL語句的名稱
-->
<sql id="fatherMapColumns">
father.id as id,
father.age as age,
father.name as name,
father.identity as identity
</sql>
<select id="selectFatherSon" resultMap="fatherSonMap">
SELECT
<include refid="fatherMapColumns"/>
FROM
t_father father
WHERE
father.name = #{name}
</select>
dao層的東西
/**
* 獲取指定姓名父親和其兒子信息
* @param name 姓名
* @return
*/
Father selectFatherSon(@Param("name")String name);
方法二:用嵌套ResultMap實現一對多映射