Mybatis framework (XII): Mybatis lazy loading

First, an overview of lazy loading

 

Second, build environment

1, create a database table

Reference "mybatis Getting Started": https://blog.csdn.net/yu1755128147/article/details/103358209

2, create a maven web project and import coordinates

3, create entity classes, persistence dao interfaces

Create a User entity class

package com.wedu.mybatis12.domain;

import java.io.Serializable;
import java.util.Date;

/**
 * 用户实体
 */
public class User implements Serializable {

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

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", address='" + address + '\'' +
                ", sex='" + sex + '\'' +
                ", birthday=" + birthday +
                '}';
    }
}

Creating an entity class Account

package com.wedu.mybatis12.domain;

import java.io.Serializable;

/**
 * 账户实体
 */
public class Account implements Serializable {

    private Integer id;
    private Integer uid;
    private Double money;


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", uid=" + uid +
                ", money=" + money +
                '}';
    }
}

Persistence Layer Interface IUserDao

package com.wedu.mybatis12.dao;

/**
 * 用户的持久层接口
 */
public interface IUserDao {

}

Persistence Layer Interface IAccountDao

package com.wedu.mybatis12.dao;

/**
 * 账户持久层接口
 */
public interface IAccountDao {

}

 4. Create a database profile: jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456

5, create a log file: log4j.properties

# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=E:\\project\\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

6, create a profile: SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--引用外部的配置文件信息-->
    <properties resource="jdbc.properties"/>

    <!--配置别名-->
    <typeAliases>
        <package name="com.wedu.mybatis12.domain"/>
    </typeAliases>

    <!--配置环境-->
    <environments default="mysql">
        <environment id="mysql">
            <!--配置事务的类型-->
            <transactionManager type="JDBC"></transactionManager>
            <!--配置数据源-->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <!--配置映射文件的位置-->
    <mappers>
        <package name="com.wedu.mybatis12.dao" />
    </mappers>
</configuration>

7, create a mapping file: IUserDao.xml and IAccountDao.xml

IUserDao.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wedu.mybatis12.dao.IUserDao">

</mapper>

IAccountDao.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wedu.mybatis12.dao.IAccountDao">

</mapper>

8, create a test class

package com.wedu.mybatis12.dao;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;

/**
 * 延迟加载测试
 */
public class UserDaoTest {

    private SqlSession session;
    private IUserDao userDao;
    private IAccountDao accountDao;

    @Before
    public void init() throws Exception{
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("SqlMapConfig.xml"));
        session = factory.openSession();
        userDao = session.getMapper(IUserDao.class);
        accountDao = session.getMapper(IAccountDao.class);
        
    }

    @After
    public void destroy() {
        session.close();
    }
}

Three, mybatis xml-based lazy loading

1, many to one

1.1, Adding User Account entity in the field

    //多对一的关系映射:从表实体应该包含一个主表实体的对象引用
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

1.2, the interface adds findALL method IAccountDao

    /**
     * 查询所有账户,,同时还要获取到当前账户的所属用户信息
     * @return
     */
    List<Account> findAll();

 1.3, adding findAll SQL statement in the IAccountDao.xml

    <!--定义封装account和user的resultMap-->
    <resultMap id="accountUserMap" type="account">
        <id property="id" column="id"></id>
        <result property="uid" column="uid"></result>
        <result property="money" column="money"></result>
        <!-- 一对一的关系映射:配置封装user的内容,select属性指定的内容:查询用户的唯一标识,column属性指定的内容:用户根据id查询时,所需要的参数的值-->
        <association property="user" column="uid" javaType="user" select="com.wedu.mybatis12.dao.IUserDao.findById" />
    </resultMap>
    <!-- 查询所有账户,,同时还要获取到当前账户的所属用户信息 -->
    <select id="findAll" resultMap="accountUserMap">
        select * from account 
    </select>

1.4, adding findById in IUserDao.xml in SQL statements 

    <!--根据id查询用户信息-->
    <select id="findById" parameterType="int" resultType="user">
        select * from user where id = #{id}
    </select>

1.5, in turn Mybatis delay loading of SqlMapConfig.xml

    <!--配置全局变量-->
    <settings>
        <!--开启Mybatis延迟加载-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>

1.6, test lazy loading in AccountDaoTest in (see the output and logs the results of implementation does not output)

    /**
     * 查询所有账户,,同时还要获取到当前账户的所属用户信息
     */
    @Test
    public void testFindAll() {
        List<Account> accounts = accountDao.findAll();
        for (Account account : accounts) {
            System.out.println(account);
            System.out.println(account.getUser());
        }
    }

 2, many

2.1, add fields in the User Account entity

    //一对多关系映射:主表实体应该包含从表实体的集合引用
    private List<Account> accounts;

    public List<Account> getAccounts() {
        return accounts;
    }

    public void setAccounts(List<Account> accounts) {
        this.accounts = accounts;
    }

2.2, an interface add findALL method in IUserDao

    /**
     * 查询所有用户,,同时获取到用户下所有账户的信息
     * @return
     */
    List<User> findAll();

2.3, adding findAll SQL statement in the IUserDao.xml

    <!--定义User的resultMap-->
    <resultMap id="userAccountMap" 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>
        <!--一对多的关系映射:配置user对象中accounts集合的映射-->
        <collection property="accounts" column="id" ofType="account" select="com.wedu.mybatis12.dao.IAccountDao.findById"/>
    </resultMap>
    <!-- 查询所有用户,,同时获取到用户下所有账户的信息 -->
    <select id="findAll" resultMap="userAccountMap">
        select * from user
    </select>

2.4, adding findById in IAccountDao.xml in SQL statements 

    <!--根据id查询账户-->
    <select id="findById" resultType="account">
        select * from account where uid = #{id}
    </select>

2.5, in turn Mybatis delay loading of SqlMapConfig.xml

    <!--配置全局变量-->
    <settings>
        <!--开启Mybatis延迟加载-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>

2.6, the test load UserDaoTest the delay (and see the output result of the execution log is not output)

    /**
     * 查询所有用户,,同时获取到用户下所有账户的信息
     */
    @Test
    public void testFindAll() {
        List<User> users = userDao.findAll();
        for (User user : users) {
            System.out.println(user);
            System.out.println(user.getAccounts());
        }
    }

Four, mybatis annotation-based lazy loading 

1, many to one

1.1, Adding User Account entity attributes

    //多对一(mybatis中称之为一对一)的映射:一个账户只能属于一个用户
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

1.2、在IAccountDao接口添加findALL方法和对应的注解

    /**
     * 查询所有账户
     * @return
     */
    @Select("select * from account")
    @Results(id = "accountMap",value = {
            @Result(id = true,column = "id",property = "id"),
            @Result(column = "uid",property = "uid"),
            @Result(column = "money",property = "money"),
            @Result(property = "user",column = "uid",one=@One(select="com.wedu.mybatis15.dao.IUserDao.findById",fetchType= FetchType.EAGER))
    })
    List<Account> findAll();

1.3、在IUserDao接口添加findById方法

    /**
     * 根据id查询用户
     * @param id
     * @return
     */
    @Select("select * from user where id=#{id}")
    User findById(Integer id);

1.4、在AccountDaoTest测试类测试延迟加载

    /**
     * 查找所有用户
     */
    @Test
    public void testFindAll() {
        //4.使用代理对象执行方法
        List<Account> accounts = accountDao.findAll();
        for(Account account : accounts){
            System.out.println(account);
            System.out.println(account.getUser());
        }
    }

2、一对多

2.1、在User实体中添加Account对象集合的属性

    //一对多关系映射:一个用户对应多个账户
    private List<Account> accounts;

    public List<Account> getAccounts() {
        return accounts;
    }

    public void setAccounts(List<Account> accounts) {
        this.accounts = accounts;
    }

2.2、在IUserDao接口添加findALL方法和对应的注解

    /**
     * 查询所有用户
     * @return
     */
    @Select("select * from user")
    @Results(id = "userMap",value = {
            @Result(id = true,column = "id",property = "id"),//@Result:映射实体类属性名和表的字段名对应关系
            @Result(column = "username",property = "username"),
            @Result(column = "birthday",property = "birthday"),
            @Result(column = "sex",property = "sex"),
            @Result(column = "address",property = "address"),
            @Result(property = "accounts",column = "id",
                    many = @Many(select = "com.wedu.mybatis15.dao.IAccountDao.findAccountById",
                            fetchType = FetchType.LAZY))
    })
    List<User> findAll();

2.3、在IAccountDao接口添加findAccountById方法

    /**
     * 根据用户id查询账户信息
     * @param id
     * @return
     */
    @Select("select * from account where uid=#{id}")
    Account findAccountById(Integer id);

2.4、在UserDaoTest测试类测试延迟加载

    /**
     * 查找所有用户
     */
    @Test
    public void testFindAll() {
        //4.使用代理对象执行方法
        List<User> users = userDao.findAll();
        for(User user : users){
            System.out.println(user);
            System.out.println(user.getAccounts());
        }
    }

 

发布了134 篇原创文章 · 获赞 10 · 访问量 7363

Guess you like

Origin blog.csdn.net/yu1755128147/article/details/103467369