MyBatis Association 實現延遲加載

一、創建數據庫 SQL

CREATE TABLE husband (husbandId INT, husbandName VARCHAR(20), husbandAge INT);
CREATE TABLE wife (wifeId INT, hId INT, wifeName VARCHAR(20), wifeAge INT);

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

public class Wife implements Serializable {

    private int wifeId;
    private int hId;
    private String wifeName;
    private int wifeAge;
    private Husband husband;
    ...
}
public class Husband implements Serializable {

    private int husbandId;
    private String husbandName;
    private int husbandAge;
    ...
}

三、持久層接口

public interface IWifeDao {

    List<Wife> findAll();
}
public interface IHusbandDao {

    Husband findById(int id);
}

四、持久層映射文件

IWifeDao.xml

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

    <resultMap type="chu.yi.bo.domain.Wife" id="wifeMap">
        <id column="wifeId" property="wifeId"/>
        <result column="hId" property="hId"/>
        <result column="wifeName" property="wifeName"/>
        <result column="wifeAge" property="wifeAge"/>
        <association property="husband" javaType="chu.yi.bo.domain.Husband"
            select="chu.yi.bo.dao.IHusbandDao.findById"
            column="hId"/>
    </resultMap>
    
    <select id="findAll" resultMap="wifeMap">
        select * from wife;
    </select>
    
</mapper>

IHusbandDao.xml

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

    <select id="findById" resultType="chu.yi.bo.domain.Husband" parameterType="int">
        select * from husband where husbandId = #{hid}
    </select>

</mapper>

五、測試

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