mybaitis学习——延迟加载
一对多在collection配置:
- property:集合属性名
- ofType : 集合中元素的全限定名类名,可以用起好的别名
- select:执行的sql语句的mapperId(唯一标识,接口的全限定类名.方法名)
- colulm:传入到sql语句中的参数(主表字段名)
- fetchType=”lazy” :开启懒加载模式
主表查询语句
<resultMap type="user" id="userLazy">
<!-- 用户主键信息 -->
<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:集合属性名
ofType : 集合中元素的全限定名类名,可以用起好的别名
select:执行的sql语句的mapperId(唯一标识,接口的全限定类名.方法名)
colulm:传入到sql语句中的参数(主表字段名)
fetchType="lazy" :开启懒加载模式
-->
<collection fetchType="lazy" property="accounts" ofType="account"
select="cn.it.demo.dao.AccountDao.findAccByUid" column="id">
</collection>
</resultMap>
<!-- 只查询当前对象 -->
<select id="findAllLazy" resultMap="userLazy">
select * from user
</select>
从表查询语句
<!-- 根据用户id查询账户 -->
<select id="findAccByUid" resultType=“account” parameterType="int">
SELECT * FROM account where uid = #{uid};
</select>
test测试类
@Test
public void testFindAllLazy() {
SqlSession session = sqlSessionFactory.openSession();
UserDao userDao = session.getMapper(UserDao.class);
List<User> users = userDao.findAllLazy();
System.out.println("未使用account属性==========================================");
for (User user : users) {
System.out.println(user.getId()+"---"+user.getUsername());
}
System.out.println("使用account属性 ===========================================================");
for (User user : users) {
System.out.println(user);
}
}
一对一
主表
<resultMap type="account" id="accountMap">
<!-- 配置账户的基本属性 -->
<id column="id" property="id"/>
<result column="uid" property="uid"/>
<result column="money" property="money"/>
<!-- 配置账户的关联对象,用户对象 -->
<association property="user" javaType="user"
select="cn.it.dao.UserDao.findUserById" column="uid"
></association>
</resultMap>
<!-- 查询全部的账户(使用延迟加载的形式加载账户所属的用户) -->
<select id="findAllAccounts" resultMap="accountMap">
select * from account
</select>
分表
<!-- 只查询当前对象 -->
<select id="findUserById" resultType="user" parameterType="int">
select * from user where id = #{userid}
</select>