**
延迟加载和立即加载
**
-
一对一(多对一):立即加载
实现立即加载: 当查询account信息时,同步查询关联的user信息配置AccountDao的xml文件,实现延迟加载
-association:Account关联的user类 -property: 实体类属性名 -column: 查询语句属性名 -select: 通过uid,查询user的方法 -javaType:user的Java类型
<resultMap id="account" type="account">
<id property="id" column="id"></id>
<result property="uid" column="id"></result>
<result property="money" column="money"></result>
<association property="user" column="uid" select="com.one.mybatis.dao.UserDao.findById" javaType="user"></association>
</resultMap>
<select id="findAll" resultMap="account">
select * from account;
</select>
- 一对多:延迟加载
实现一对多的延迟加载。当查询User表时,按需加载关联的多个Account信息
<resultMap id="user" type="user">
<id property="id" column="id"></id>
<result property="username" column="username"></result>
<result property="birthday" column="birthday"></result>
<result property="sex" column="sex"></result>
<result property="address" column="address"></result>
<collection property="accounts" column="id" select="com.one.mybatis.dao.AccountDao.findByUid" ofType="account">
</collection>
</resultMap>
<select id="findAll" resultMap="user">
select * from user;
</select>
com.one.mybatis.dao.AccountDao.findByUid实现:
<select id="findByUid" resultType="account" parameterType="int">
select * from account where uid=#{uid};
</select>
- 多对多:延迟加载
查询user信息时,延迟加载想关联的多个role信息
<resultMap id="user" type="user">
<id property="id" column="id"></id>
<result property="username" column="username"></result>
<result property="birthday" column="birthday"></result>
<result property="sex" column="sex"></result>
<result property="address" column="address"></result>
<collection property="roles" column="id" select="com.one.mybatis.dao.RoleDao.findByUid" ofType="role"></collection>
</resultMap>
<select id="findAll" resultMap="user">
select * from user;
</select>
com.one.mybatis.dao.RoleDao.findByUid方法:
<select id="findByUid" parameterType="int" resultType="role">
select * from role, user_role where role.id=user_role.rid and user_role.uid=#{uid};
</select>