MyBatis Collection 實現延遲加載

一、創建數據庫 SQL

CREATE TABLE father (fatherId INT, fatherName VARCHAR(20), fatherAge INT);
CREATE TABLE son (sonId INT, fId INT, sonName VARCHAR(20), sonAge INT);

二、創建與數據庫表對應的實體類

public class Father implements Serializable {

    private int fatherId;
    private String fatherName;
    private int fatherAge;
    private List<Son> sonList;
    ...
}
public class Son implements Serializable {

    private int sonId;
    private int fId;
    private String sonName;
    private int sonAge;
	...
}

三、持久層接口

public interface IFatherDao {
    List<Father> findAll();
}
public interface ISonDao {
    Son findById(int id);
}

四、持久層映射文件

IFatherDao.xml

<mapper namespace="chu.yi.bo.dao.IFatherDao">

    <resultMap id="fatherMap" type="chu.yi.bo.domain.Father">
        <id column="fatherId" property="fatherId"/>
        <result column="fatherName" property="fatherName"/>
        <result column="fatherAge" property="fatherAge"/>
        <collection property="sonList" ofType="chu.yi.bo.domain.Son"
            select="chu.yi.bo.dao.ISonDao.findById"
            column="fatherId"/>
    </resultMap>

    <select id="findAll" resultMap="fatherMap">
        select * from father;
    </select>
</mapper>

ISonDao.xml

<mapper namespace="chu.yi.bo.dao.ISonDao">
    <select id="findById" resultType="chu.yi.bo.domain.Son" parameterType="int">
        select * from son where fId = #{fatherId}
    </select>
</mapper>

五、測試

List<Father> fatherList = iFatherDao.findAll();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章