1.首先修改配置文件信息,开启mybatis的延迟加载功能
设置代码如下
<settings>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
2.需求分析
查询出所有用户信息,实现用户下的账户的懒加载功能
3.代码的实现
(1)实体类对象两个(一个是用户表信息,一个是账户表的信息,他们是一对多的关系,一个用户可以有多个账户)
/** Title: Account
Description: 账户的实体类
*/
public class Account implements Serializable {
private Integer id;
private Integer uid;
private Double money;
//下面是get和set方法
}
/**
Title: User
Description: 用户的实体类
*/
public class User implements Serializable {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
private List<Account> accounts;
//下面是get和set方法
}
(2)dao层的代码
/**
* 查询所有用户,同时获取出每个用户下的所有账户信息
* @return
*/
public interface IUserDao {
List<User> findAll();
}
/**
根据用户 id 查询账户信息
@param uid
@return */
public interface IAccountDao {
List<Account> findByUid(Integer uid);
}
//user实体类的映射文件查询代码
<resultMap type="user" id="userMap">
<id column="id" property="id"></id>
<result column="username" property="username"/>
<result column="address" property="address"/>
<result column="sex" property="sex"/>
<result column="birthday" property="birthday"/>
<!-- collection 是用于建立一对多中集合属性的对应关系
ofType 用于指定集合元素的数据类型
select 是用于指定查询账户的唯一标识(账户的 dao 全限定类名加上方法名称)
column 是用于指定使用哪个字段的值作为条件查询 -->
<collection property="accounts" ofType="account"
select="com.itheima.dao.IAccountDao.findByUid" column="id">
</collection>
</resultMap>
<!-- 配置查询所有操作 -->
<select id="findAll" resultMap="userMap">
select * from user
</select>
备注: collection标签: 主要用于加载关联的集合对象 select 属性: 用于指定查询 account 列表的 sql 语句,所以填写的是该 sql 映射的 id column 属性: 用于指定 select 属性的 sql 语句的参数来源,上面的参数来自于 user 的 id 列,所以就写成 id 这一 个字段名了
//账户对象的映射文件代码的编写
<!-- 根据用户 id 查询账户信息 -->
<select id="findByUid" resultType="account" parameterType="int">
select * from account where uid = #{uid}
</select>