欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Mybatis学习记录--延迟加载Lazyloading 和缓存机制ehcache

程序员文章站 2022-05-02 10:07:42
...

1, 声明

本博客所有内容来源于网络、书籍、和各类手册。
内容均为非盈利,旨为学习记录,方便查询、总结备份、开源分享。
部分转载内容均有注明出处,如有侵权请告知,马上删除.

2,参考链接

Mybatis(五) 延迟加载和缓存机制(一级二级缓存)
MyBatis-23MyBatis缓存配置【二级缓存】
Windows 启动 Idea 报错 if you already hava a 64-bit JDK…以及 failed to create jvm…

3, maven依赖管理

添加日志管理报log4j 和slf4j,桥接jar包slf4j-log4j12

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.hardes</groupId>
  <artifactId>MybatisEntry7_LazyLoad</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>MybatisEntry7_LazyLoad</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    <!-- spring版本号 -->
    <spring.version>5.1.9.RELEASE</spring.version>
    <!-- Mybatis版本号 -->
    <mybatis.version>3.4.6</mybatis.version>
    <!-- log4j 版本号 -->
    <log4j.version>1.2.17</log4j.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!-- spring核心包 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-oxm</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.4</version>
    </dependency>
    <!-- mybatis核心包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <!-- mybatis/spring包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.2</version>
    </dependency>

    <!-- 导入Mysql数据库链接jar包 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.16</version>
    </dependency>

    <!-- 日志文件管理包 -->
    <!-- log start -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>

    <!-- slf4j日志包-->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.25</version>
    </dependency>
    <!-- slf4j+ log4j桥接 日志包-->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.25</version>
      <scope>test</scope>
    </dependency>


    <!-- 缓存框架(ehcache) -->
    <dependency>
      <groupId>net.sf.ehcache</groupId>
      <artifactId>ehcache-core</artifactId>
      <version>2.6.11</version>
    </dependency>

    <!-- 缓存框架(mybatis整合ehcache)-->
    <dependency>
      <groupId>org.mybatis.caches</groupId>
      <artifactId>mybatis-ehcache</artifactId>
      <version>1.1.0</version>
    </dependency>

  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
        </includes>
      </resource>
    </resources>
  </build>
</project>

4, 工具

Idea 2019.2
maven 3.61
mysql 8.017
mybatis
Navicat

5,代码结构

Mybatis学习记录--延迟加载Lazyloading 和缓存机制ehcache

6, Mybatis Generator 配置文件

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>

    <settings>
        <!-- 用于输出日志 log4j:LOG4J SLF4J -->
        <setting name="logImpl" value="SLF4J"/>
        <!--打开延迟加载的开关,默认为true-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!--积极的懒加载,默认是true,设置为false时,懒加载生效-->
        <setting name="aggressiveLazyLoading" value="false"/>
        <!--开启二级缓存总开关-->
        <setting name="cacheEnabled" value="true"/>
    </settings>

    <typeAliases>
        <!-- 别名为类名首字母大小写都可以 -->
        <package name="com.hardes.pojos"/>
    </typeAliases>


    <!-- 原先这里还有连接数据库的一些配置,与spring整合后,都交由spring来管理 -->
    <!-- 加载mapper映射文件,使用通用的配置 -->
    <mappers>
        <package name="com.hardes.mappers"/>
    </mappers>

</configuration>

7, ehcache.xml

放置在resource 路径下面

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
    <!-- 缓存数据要存放的磁盘地址 -->
    <diskStore path="D:\CM_Library\java\maven\ehcache" />
    <!-- diskStore:指定数据在磁盘中的存储位置。  defaultCache:当借助CacheManager.add("demoCache")创建Cache时,EhCache便会采用<defalutCache/>指定的的管理策略
        以下属性是必须的:  maxElementsInMemory - 在内存中缓存的element的最大数目  maxElementsOnDisk
        - 在磁盘上缓存的element的最大数目,若是0表示无穷大  eternal - 设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断
         overflowToDisk - 设定当内存缓存溢出的时候是否将过期的element缓存到磁盘上 以下属性是可选的:  timeToIdleSeconds
        - 当缓存在EhCache中的数据前后两次访问的时间超过timeToIdleSeconds的属性取值时,这些数据便会删除,默认值是0,也就是可闲置时间无穷大
         timeToLiveSeconds - 缓存element的有效生命期,默认是0.,也就是element存活时间无穷大 diskSpoolBufferSizeMB
        这个参数设置DiskStore(磁盘缓存)的缓存区大小.默认是30MB.每个Cache都应该有自己的一个缓冲区.  diskPersistent
        - 在VM重启的时候是否启用磁盘保存EhCache中的数据,默认是false。  diskExpiryThreadIntervalSeconds
        - 磁盘缓存的清理线程运行间隔,默认是120秒。每个120s,相应的线程会进行一次EhCache中数据的清理工作  memoryStoreEvictionPolicy
        - 当内存缓存达到最大,有新的element加入的时候, 移除缓存中element的策略。默认是LRU(最近最少使用),可选的有LFU(最不常使用)和FIFO(先进先出) -->

    <!--defaultCache元素将仅在以编程方式创建缓存而未指定配置时使用-->
    <defaultCache maxElementsInMemory="1000"
                  maxElementsOnDisk="10000000" eternal="false" overflowToDisk="true"
                  timeToIdleSeconds="120" timeToLiveSeconds="120"
                  diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU">
    </defaultCache>
    <!--  定义alldatas缓存
    <cache name="alldatas" maxEntriesLocalHeap="1000" eternal="false"
           timeToIdleSeconds="21600" timeToLiveSeconds="21600" memoryStoreEvictionPolicy="LRU"
           overflowToDisk="true"
           diskPersistent="false"
           diskExpiryThreadIntervalSeconds="120">

    </cache>
    -->

</ehcache>

8, Spring配置文件

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd ">
    <!-- 引用java配置文件 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>


    <!-- 配置数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${db.driver}"/>
        <property name="url" value="${db.url}"/>
        <property name="username" value="${db.username}"/>
        <property name="password" value="${db.password}"/>
        <property name="maxActive" value="10"/>
        <property name="maxIdle" value="5"/>
    </bean>

    <!-- 配置SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 指定mybatis的全局配置文件的路径 -->
        <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property>
        <!-- 数据源 -->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 批量配置,这里是批量配置mapper代理,那么下面就不用配置id了。
       我们想要获取哪个mapper代理用这个格式:类名首字母小写
    -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.hardes.mappers"></property>
        <!-- 默认不需要配置,但是如果有多个数据源的配置,那么就需要配置此项 -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

</beans>

9, properties

jdbc.properties

db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql:///test?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=UTC
db.username=root
db.password=root

log4j.properties

# Global logging configuration
# 在开发环境下日志级别建议设置为DEBUG,生产环境设置成INFO或ERROR
log4j.rootLogger=DEBUG, stdout
# Console output
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPat

10, mappers

OrdersMapper.java

package com.hardes.mappers;

import com.hardes.pojos.Orders;
import com.hardes.pojos.OrdersExt;
import com.hardes.pojos.Users;

import java.util.List;

public interface OrdersMapper {

    List<OrdersExt> findOrdersAndUsersByOid1(int i);
    List<Orders> findOrdersAndUserLazyloading();

}

OrdersMapper.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">
<!--
    namespace命名空间,作用就是对sql进行分类化管理,将sql隔离
    注意:使用mapper代理方法开发,namespace有特殊重要的作用,namespace为对应的mapper接口地址
-->
<mapper namespace="com.hardes.mappers.OrdersMapper">
    <!--开启二级缓存你,默认使用PerpetualCache-->
    <cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

    <!--一对一映射,还用resultType-->
    <select id="findOrdersAndUsersByOid1" parameterType="int" resultType="com.hardes.pojos.OrdersExt">
        SELECT *

        FROM users,orders WHERE  orders.id=#{oid} AND orders.user_id= users.id
    </select>



   <resultMap id="OrdersAndUserLazyloading" type="com.hardes.pojos.Orders">
       <id column="orders_id"  property="oid"/>
       <result column="number" property="number"/>
       <result  column="user_id" property="user_id"/>
       <!-- users为Orders类中的属性-->
       <association property="users"
                    column="user_id"
                    select="com.hardes.mappers.UsersMapper.findUserById"/>
   </resultMap>

    <select id="findOrdersAndUserLazyloading" resultMap="OrdersAndUserLazyloading" useCache="true" flushCache="false">
        SELECT
        orders.id orders_id,
        orders.number,
        orders.user_id,
        orders.*

        FROM orders
    </select>


</mapper>

UsersMapper.java

package com.hardes.mappers;

import com.hardes.pojos.Users;

import java.util.List;

public interface UsersMapper {

    List<Users> findOrdersAndUsersByOid2(int id);
    List<Users>   findUserById(int i);
}


UsersMapper.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">
<!--
    namespace命名空间,作用就是对sql进行分类化管理,将sql隔离
    注意:使用mapper代理方法开发,namespace有特殊重要的作用,namespace为对应的mapper接口地址
-->
<mapper namespace="com.hardes.mappers.UsersMapper">
    <!--开启二级缓存你,默认使用PerpetualCache-->
     <cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

    <resultMap id="findOrdersAndUsersReM" type="com.hardes.pojos.Users">
        <id column="uid" property="id"/>
        <result column="username" property="username"/>
        <result column="sex" property="sex"/>

        <!-- orders为Users类中的属性-->
        <association property="orders" javaType="com.hardes.pojos.Orders">
            <id column="oid" property="id"/>
            <result column="number" property="number"/>
            <result column="user_id" property="userId"/>
            <result column="time"   property="time"/>
        </association>
    </resultMap>

    <select id="findOrdersAndUsersByOid2" parameterType="int" resultMap="findOrdersAndUsersReM">
        SELECT
            users.id uid,
            users.username,
            users.sex,
            orders.id oid,
            orders.number,
            orders.user_id,
            orders.time

         FROM users,orders WHERE  users.id=#{id} AND users.id=orders.user_id
    </select>

<!--lazy loading-->
    <select id="findUserById"   parameterType="int" resultType="com.hardes.pojos.Users"  useCache="true" flushCache="false">
        SELECT *
        FROM    users
        WHERE id=#{id}
    </select>



</mapper>

11, pojos类

Items.java

package com.hardes.pojos;

import java.util.Date;

public class Items {
    private Integer id;
    private String name;
    private String detail;
    private Float price;
    private String pic;
    private Date time;

    //订单项集合
    //private List<Orders_detail> orders_detailList;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDetail() {
        return detail;
    }

    public void setDetail(String detail) {
        this.detail = detail;
    }

    public Float getPrice() {
        return price;
    }

    public void setPrice(Float price) {
        this.price = price;
    }

    public String getPic() {
        return pic;
    }

    public void setPic(String pic) {
        this.pic = pic;
    }

    public Date getTime() {
        return time;
    }

    public void setTime(Date time) {
        this.time = time;
    }
}

Orders.java

package com.hardes.pojos;

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


public class Orders implements Serializable {
    private Integer oid;
    private Integer user_id;
    private String number;
    private Date time;
    private String note;
    private Users users;
    
    //订单明细集合
   // private List<Orders_detail> detailList;


    public Integer getOid() {
        return oid;
    }

    public void setOid(Integer oid) {
        this.oid = oid;
    }

    public Integer getUser_id() {
        return user_id;
    }

    public void setUser_id(Integer user_id) {
        this.user_id = user_id;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public Date getTime() {
        return time;
    }

    public void setTime(Date time) {
        this.time = time;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }

    public Users getUsers() {
        return users;
    }

    public void setUsers(Users users) {
        this.users = users;
    }

    @Override
    public String toString() {
        return "Orders{" +
                "oid=" + oid +
                ", user_id=" + user_id +
                ", number='" + number + '\'' +
                ", time=" + time +
                ", note='" + note + '\'' +
                ", users=" + users +
                '}';
    }
}

Orders_detail.java

package com.hardes.pojos;

public class Orders_detail {
    private Integer id;
    private Integer ordersId;
    private Integer itemsId;
    private Integer itemsNum;
    //商品信息
   //private Items items;

    public Integer getId() {
        return id;
    }

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

    public Integer getOrdersId() {
        return ordersId;
    }

    public void setOrdersId(Integer ordersId) {
        this.ordersId = ordersId;
    }

    public Integer getItemsId() {
        return itemsId;
    }

    public void setItemsId(Integer itemsId) {
        this.itemsId = itemsId;
    }

    public Integer getItemsNum() {
        return itemsNum;
    }

    public void setItemsNum(Integer itemsNum) {
        this.itemsNum = itemsNum;
    }

    @Override
    public String toString() {
        return "Orders_detail{" +
                "id=" + id +
                ", ordersId=" + ordersId +
                ", itemsId=" + itemsId +
                ", itemsNum=" + itemsNum +
                '}';
    }
}

OrdersExt.java

package com.hardes.pojos;


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

public class OrdersExt extends Orders implements Serializable {
    private String username;
    private Date birthday;
    private char sex;
    private String address;



    public String getUsername() {
        return username;
    }

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

    public Date getBirthday() {
        return birthday;
    }

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

    public char getSex() {
        return sex;
    }

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

    public String getAddress() {
        return address;
    }

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

    @Override
    public String toString() {
        return "OrdersExt{" +
                "username='" + username + '\'' +
                ", birthday=" + birthday +
                ", sex=" + sex +
                ", address='" + address + '\'' +
                ", "+super.toString()+

                '}';
    }
}

Users.java

package com.hardes.pojos;

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

public class Users implements Serializable {
    private int id;
    private String username;
    private String sex;
    private Date birthday;
    private String address;
    //private Orders orders;
    //订单信息集合
   // private List<Orders> ordersList;



    public int getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

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

    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;
    }

    public String getAddress() {
        return address;
    }

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

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

12, 测试文件

package com.hardes;

import com.hardes.mappers.OrdersMapper;
import com.hardes.pojos.Orders;
import com.hardes.pojos.OrdersExt;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class TestUsers1 {
    @Test
    public void userTest1(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("spring/applicationContext.xml");
        /**
         * 使用resultType作映射,查询订单orders 并关联users的信息
         */
        OrdersMapper ordersmapper= (OrdersMapper) ac.getBean("ordersMapper");

        List<OrdersExt> list = ordersmapper.findOrdersAndUsersByOid1(2);

        System.out.println(list);

        //只查询了一次sql,所以第二次访问是从ehcache缓存中拿的

        List<OrdersExt> list3 = ordersmapper.findOrdersAndUsersByOid1(2);

        System.out.println(list3);


        /**
         * 使用resultType作映射,lazy loading
         */
        List<Orders> list1 = ordersmapper.findOrdersAndUserLazyloading();

        System.out.println(list1);
         //只查询了一次sql,所以第二次访问是从ehcache缓存中拿的
        List<Orders> list2 = ordersmapper.findOrdersAndUserLazyloading();

        System.out.println(list2);

    }

}

Note

测试文件中的第一个是对resultMap作为映射的相关联查询,同时增加了list3作为检验ehcache框架的测试
/**
* 使用resultType作映射,查询订单orders 并关联users的信息
*/

      OrdersMapper ordersmapper= (OrdersMapper) ac.getBean("ordersMapper");

        List<OrdersExt> list = ordersmapper.findOrdersAndUsersByOid1(2);

        System.out.println(list);

        //只查询了一次sql,所以第二次访问是从ehcache缓存中拿的

        List<OrdersExt> list3 = ordersmapper.findOrdersAndUsersByOid1(2);

        System.out.println(list3);

第二个测试项目才是延迟加载和缓存机制的测试,增加list2作为ehcache框架的测试

        /**
         * 使用resultType作映射,lazy loading
         */
        List<Orders> list1 = ordersmapper.findOrdersAndUserLazyloading();

        System.out.println(list1);
         //只查询了一次sql,所以第二次访问是从ehcache缓存中拿的
        List<Orders> list2 = ordersmapper.findOrdersAndUserLazyloading();

        System.out.println(list2);

13, 测试结果

DEBUG [main] - JDBC Connection [jdbc:mysql:///test?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=UTC, aaa@qq.com, MySQL Connector/J] will not be managed by Spring
DEBUG [main] - ==>  Preparing: SELECT * FROM users,orders WHERE orders.id=? AND orders.user_id= users.id 
DEBUG [main] - ==> Parameters: 2(Integer)
DEBUG [main] - <==      Total: 1
DEBUG [main] - put added 0 on heap
DEBUG [main] - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@35038141]
[OrdersExt{username='Tom', birthday=Sun Oct 06 08:00:00 SGT 2019, sex=M, address='Jurong East', Orders{oid=null, user_id=1, number='2000', time=Mon Oct 07 21:47:26 SGT 2019, note='bread', users=null}}]
DEBUG [main] - Creating a new SqlSession
DEBUG [main] - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1c12f3ee] was not registered for synchronization because synchronization is not active
DEBUG [main] - Cache Hit Ratio [com.hardes.mappers.OrdersMapper]: 0.5
DEBUG [main] - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1c12f3ee]
[OrdersExt{username='Tom', birthday=Sun Oct 06 08:00:00 SGT 2019, sex=M, address='Jurong East', Orders{oid=null, user_id=1, number='2000', time=Mon Oct 07 21:47:26 SGT 2019, note='bread', users=null}}]
DEBUG [main] - Creating a new SqlSession
DEBUG [main] - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6d467c87] was not registered for synchronization because synchronization is not active
DEBUG [main] - Cache Hit Ratio [com.hardes.mappers.OrdersMapper]: 0.3333333333333333
DEBUG [main] - Fetching JDBC Connection from DataSource
DEBUG [main] - JDBC Connection [jdbc:mysql:///test?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=UTC, aaa@qq.com, MySQL Connector/J] will not be managed by Spring
DEBUG [main] - ==>  Preparing: SELECT orders.id orders_id, orders.number, orders.user_id, orders.* FROM orders 
DEBUG [main] - ==> Parameters: 
DEBUG [com%002ehardes%002emappers%002e%004frders%004dapper.data] - fault removed 0 from heap
DEBUG [com%002ehardes%002emappers%002e%004frders%004dapper.data] - fault added 0 on disk
DEBUG [main] - <==      Total: 3
DEBUG [main] - put added 0 on heap
DEBUG [main] - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6d467c87]
DEBUG [main] - Cache Hit Ratio [com.hardes.mappers.UsersMapper]: 0.0
DEBUG [main] - Fetching JDBC Connection from DataSource
DEBUG [main] - JDBC Connection [jdbc:mysql:///test?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=UTC, aaa@qq.com, MySQL Connector/J] will not be managed by Spring
DEBUG [main] - ==>  Preparing: SELECT * FROM users WHERE id=? 
DEBUG [main] - ==> Parameters: 3(Integer)
DEBUG [main] - <==      Total: 1
DEBUG [main] - put added 0 on heap
DEBUG [main] - Cache Hit Ratio [com.hardes.mappers.UsersMapper]: 0.0
DEBUG [main] - Fetching JDBC Connection from DataSource
DEBUG [main] - JDBC Connection [jdbc:mysql:///test?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=UTC, aaa@qq.com, MySQL Connector/J] will not be managed by Spring
DEBUG [main] - ==>  Preparing: SELECT * FROM users WHERE id=? 
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [com%002ehardes%002emappers%002e%0055sers%004dapper.data] - fault removed 0 from heap
DEBUG [com%002ehardes%002emappers%002e%0055sers%004dapper.data] - fault added 0 on disk
DEBUG [main] - <==      Total: 1
DEBUG [main] - put added 0 on heap
DEBUG [main] - Cache Hit Ratio [com.hardes.mappers.UsersMapper]: 0.0
DEBUG [main] - Fetching JDBC Connection from DataSource
DEBUG [com%002ehardes%002emappers%002e%0055sers%004dapper.data] - fault removed 0 from heap
DEBUG [com%002ehardes%002emappers%002e%0055sers%004dapper.data] - fault added 0 on disk
DEBUG [main] - JDBC Connection [jdbc:mysql:///test?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=UTC, aaa@qq.com, MySQL Connector/J] will not be managed by Spring
DEBUG [main] - ==>  Preparing: SELECT * FROM users WHERE id=? 
DEBUG [main] - ==> Parameters: 2(Integer)
DEBUG [main] - <==      Total: 1
DEBUG [main] - put added 0 on heap
[Orders{oid=1, user_id=3, number='1000', time=Sun Nov 03 21:46:51 SGT 2019, note='eggs', users=Users{id=3, username='sun liu', sex='M', birthday=Tue Aug 27 08:00:00 SGT 2019, address='Woodland Drive'}}, Orders{oid=2, user_id=1, number='2000', time=Mon Oct 07 21:47:26 SGT 2019, note='bread', users=Users{id=1, username='Tom', sex='M', birthday=Sun Oct 06 08:00:00 SGT 2019, address='Jurong East'}}, Orders{oid=3, user_id=2, number='3000', time=Tue Jun 22 23:54:56 SGT 2010, note='Prata', users=Users{id=2, username='Jerry', sex='F', birthday=Mon Jul 08 08:00:00 SGT 2019, address='Tampines West'}}]
DEBUG [main] - Creating a new SqlSession
DEBUG [main] - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5b5c0057] was not registered for synchronization because synchronization is not active
DEBUG [main] - Cache Hit Ratio [com.hardes.mappers.OrdersMapper]: 0.5
DEBUG [main] - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5b5c0057]
DEBUG [com%002ehardes%002emappers%002e%004frders%004dapper.data] - fault removed 0 from heap
DEBUG [com%002ehardes%002emappers%002e%004frders%004dapper.data] - fault added 0 on disk
[Orders{oid=1, user_id=3, number='1000', time=Sun Nov 03 21:46:51 SGT 2019, note='eggs', users=Users{id=3, username='sun liu', sex='M', birthday=Tue Aug 27 08:00:00 SGT 2019, address='Woodland Drive'}}, Orders{oid=2, user_id=1, number='2000', time=Mon Oct 07 21:47:26 SGT 2019, note='bread', users=Users{id=1, username='Tom', sex='M', birthday=Sun Oct 06 08:00:00 SGT 2019, address='Jurong East'}}, Orders{oid=3, user_id=2, number='3000', time=Tue Jun 22 23:54:56 SGT 2010, note='Prata', users=Users{id=2, username='Jerry', sex='F', birthday=Mon Jul 08 08:00:00 SGT 2019, address='Tampines West'}}]
DEBUG [com%002ehardes%002emappers%002e%0055sers%004dapper.data] - fault removed 0 from heap
DEBUG [com%002ehardes%002emappers%002e%0055sers%004dapper.data] - fault added 0 on disk

指定的路径生成了缓存数据
Mybatis学习记录--延迟加载Lazyloading 和缓存机制ehcache

Mybatis学习记录--延迟加载Lazyloading 和缓存机制ehcache

Mybatis学习记录--延迟加载Lazyloading 和缓存机制ehcache