MyBatis的懒加载
XML配置方式的实现:
一对一关系的实现
// Account实体类
public class Account {

private Integer id;
private Integer uid;
private Double money;
private User user;

// ...........
}

// IUserDao接口
public interface IUserDao {

// 根据id查用户
User findUserById(Integer id);

}

// IAccountDao接口
public interface IAccountDao {

// 只查询账户信息的DAO接口
List<Account> findAccount();

}
<!--IAccountDao.xml-->
<select id="findAccount" resultMap="accountMap">

SELECT * from account
</select>

<resultMap id="accountMap" type="account">
    <id column="id" property="id"/>
    <result column="uid" property="uid"/>
    <result column="money" property="money"/>

    <!-- select:  填写我们要调用的 select 映射的 id
         column : 填写我们要传递给 select 映射的参数
     -->

    <association property="user" javaType="user" select="fun.chenqi.ssm.dao.IUserDao.findUserById" column="uid"
                 fetchType="lazy"/>
</resultMap>

<!--IUserDao.xml-->
<select id="findUserById" resultType="user">

    SELECT * from user WHERE id = #{id}
</select>

一对多关系实现
// User实体类
public class User implements Serializable {

private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;

private List<Account> accounts;

// ...........

// IUserDao接口
public interface IUserDao {

// 查询所有User
List<User> findUser();

}

// IAccountDao接口
public interface IAccountDao {

  // 根据uid查用户信息
List<Account> findAccountByUid(Integer uid);

}
<!--IUserDao.xml-->
<select id="findUser" resultMap="userMap">

    SELECT * from user;
</select>
<resultMap id="userMap" type="user">
    <id column="id" property="id"/>
    <result column="username" property="username"/>
    <result column="birthday" property="birthday"/>
    <result column="sex" property="sex"/>
    <result column="address" property="address"/>

    <collection property="accounts" ofType="account" fetchType="lazy"
                select="fun.chenqi.ssm.dao.IAccountDao.findAccountByUid" column="id">
       <!-- 可以省略
        <id column="id" property="id"/>
        <result property="uid" column="uid"/>
        <result property="money" column="money"/>-->
    </collection>
</resultMap>

<!--IAccountDao.xml-->

<select id="findAccountByUid" resultType="Account" parameterType="int">
    SELECT * from account WHERE uid  = #{id}
</select>
最后修改:2019 年 07 月 29 日 07 : 02 PM