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();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值