【尚硅谷】MyBatis(一)

一、MyBatis入门 + 接口式编程(idea实现)

1、由于是入门级demo,所以直接弄个java工程,也不用maven了
先来看工程的目录结构
在这里插入图片描述
这里学习下
java中build path是什么?
如果你只是将jar包复制到Java工程里面去,那么是无法使用到jar包里面的类,因为编程ide无法找到jar包。所以build path其实就是添加jar包的路径,让ide可以找到这个路径对应的jar包的文件,从而来能够使用jar包中的方法。

2、实体类

@Data
public class Employee {
   
   private Integer id;
   private String lastName;
   private String email;
   private String gender;
}

3、mybatis的全局配置文件

<?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>
   <environments default="development">
      <environment id="development">
         <transactionManager type="JDBC" />
         <dataSource type="POOLED">
            <property name="driver" value="com.mysql.jdbc.Driver" />
            <property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
            <property name="username" value="root" />
            <property name="password" value="houchen" />
         </dataSource>
      </environment>
   </environments>
   <!-- 将我们写好的sql映射文件(EmployeeMapper.xml)
   一定要注册到全局配置文件(mybatis-config.xml)中 -->
   <mappers>
      <mapper resource="EmployeeMapper.xml" />
   </mappers>
</configuration>

4、sql映射文件 + mapper接口

<?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.atguigu.mybatis.mapper.EmployeeMapper">
<!-- 
namespace:名称空间;指定为接口的全类名
id:唯一标识
resultType:返回值类型
#{id}:从传递过来的参数中取出id值

public Employee getEmpById(Integer id);
 -->
   <select id="getEmpById" resultType="com.atguigu.mybatis.bean.Employee">
      select id,last_name lastName,email,gender from tbl_employee where id = #{id}
   </select>
</mapper>
public interface EmployeeMapper {

    public Employee getEmpById(int id);
}

5、测试代码

/*
    1、sqlSession代表和数据库的一次会话,用完必须关闭
    2、SqlSession是非线程安全的,每次使用都应该创建一个新的对象
    3、mapper接口没有实现类,但是mybatis会为这个接口生成一个代理对象
    4、两个重要的配置文件:
        mybatis的全局配置文件
        sql映射文件
 */
public class MybatisTest {

    public SqlSessionFactory getSqlSessionFactory() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        return sqlSessionFactory;
    }


    /*
     * 1、根据xml配置文件(mybatis的全局配置文件)创建一个SqlSessionFactory对象
     * 2、sql映射文件
     * 3、将sql映射文件注册到mybatis全局配置文件
     */
    @Test
    public void test() throws IOException {
        SqlSession openSession = getSqlSessionFactory().openSession();
        try {
            Employee employee = openSession.selectOne(
                    "com.atguigu.mybatis.dao.EmployeeMapper.getEmpById", 1);
            System.out.println(employee);
        } finally {
            openSession.close();
        }
    }

    @Test
    public void testMapper() throws IOException {
        SqlSession openSession = getSqlSessionFactory().openSession();
        EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
        Employee e = mapper.getEmpById(1);
        System.out.println(e);
    }
}

在这里插入图片描述

二、全局配置文件详解

1、peoperties

mybatis可以使用properties来引入外部properties配置文件的内容

  • resource:引入类路径下的资源
  • url:引入网络或者磁盘路径下的资源
    在这里插入图片描述

2、settings

这是mybatis中极为重要的调整设置,他们会改变mybatis的运行时行为

<!-- 设置转驼峰
settings:所有的设置项
setting :每个设置项
-->
<settings>
   <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>

3、typeAliases 取别名

<!--别名处理器 typeAliases 为某个类型起别名  别名不区分大小写-->
<typeAliases>
   <!--
   typeAlias : 为某个java类型取别名
      type: 指定要娶别名的类型的全类名,默认别名时类名小写employee
      alias: 指定新的别名
   -->
   <!--<typeAlias type="com.atguigu.mybatis.bean.Employee" alias="emp"></typeAlias>-->

   <!--批量起别名
      name :指定包名(为当前包已经下面所有子包的所有类起一个默认别名,类名小写)
   -->
   <package name="com.atguigu.mybatis.bean"/>
</typeAliases>

4、typeHandlers_类型处理器

处理 java 类型和数据库字段类型的一个处理器,见我的博客
https://blog.csdn.net/hc1285653662/article/details/126715783

5、plugins_插件简介

6、environments

<!--
   mybatis 可以配置多种环境  default指定使用某种环境
   environment :配置具体的环境信息,必须有两个标签:transactionManager dataSource
      id: 是环境的唯一标识
      transactionManager: 事务管理器
         type : JDBC|MANAGED 事务管理器的类型

      dataSource: 数据源
         type: UNPOOLED|POOLED|JNDI
-->
<environments default="development">
   <environment id="development">
      <transactionManager type="JDBC" />
      <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>

7、databaseIdProvider_多数据库支持

<!--
   databaseIdProvider : 支持多数据库厂商
   mybatis 根据数据库厂商的标识来执行不同的sql
-->
<databaseIdProvider type="DB_VENDOR">
   <property name="MySQL" value="mysql"/> //支持mysql环境
   <property name="Oracle" value="oracle"/> //支持oracle环境
</databaseIdProvider>

databaseId:告诉mybatis 这条语句是在什么环境下执行的

<select id="getEmpById" resultType="employee" databaseId="mysql">
   select id,last_name,email,gender from tbl_employee where id = #{id}
</select>

8、mappers

<!-- 将我们写好的sql映射文件(EmployeeMapper.xml)
一定要注册到全局配置文件(mybatis-config.xml)中 -->
<!--
   将sql映射注册到 mybatis 全局配置文件中
   mapper: 注册一个sql映射
      resource:引用类路径下的sql映射文件
      url : 引用网络路径或者磁盘路径下的sql映射文件

      class : 引用接口
         1、映射文件名和接口同名,并且与接口放在同一路径下
         2、没有sql映射文件,所有的sql都是利用注解写在接口上

         推荐:
         比较重要的,复杂的dao接口,我们来写sql映射文件
         不重要,简单的sql文件我们利用注解写在接口上

      package: 批量注册
      映射文件名和接口同名,
      并且与接口放在同一路径下

-->
<mappers>
   <!--<mapper resource="EmployeeMapper.xml" />-->
   <!--<mapper class="com.atguigu.mybatis.mapper.EmployeeMapper"></mapper>-->
   <package name="com.atguigu.mybatis.mapper"/>
</mappers>

三、Mybatis- 映射文件

1、insert_获取自增主键的值

<!-- 增加
    mybatis 也是利用 statement.getGeneratedKeys()来获取自增主键值
    useGeneratedKeys ="true" 使用自增主键获取主键值策略
    keyProperty : mybatis获取到主键值后,将其封装到java bean的哪个属性
-->
<insert id="addEmp" parameterType="com.atguigu.mybatis.bean.Employee" useGeneratedKeys="true"
   keyProperty="id">
   insert into tbl_employee(last_name,email,gender)
   values(#{lastName},#{email},#{gender})
</insert>

2、insert:获取非自增主键的值selectKey

<!--
      oracle 不支持自增: Oracle 使用序列来模拟自增
      每次插入的数据的主键是从序列中拿到的值,那么如何获取到这个值
  -->
  <insert id="addEmp" databaseId="oracle">
      /*
      keyProperty: 查出的主键值封装到javaBean的哪个属性
      order = "BEFORE" 当前sql在插入sql之前运行
              "AFTER"  当前sql在插入sql之后运行
      resultType : 查出的数据的返回值类型
      */
      <selectKey keyProperty="id" order="BEFORE" resultType="Integer">
          /*编写查询主键的sql语句*/
          select employees_seq.nextval from dual;
      </selectKey>
      /*插入的主键是从序列中拿到的*/
      insert into employees(id,last_name,email,gender)
values(#{lastName},#{email},#{gender})
  </insert>

3、mybatis参数处理

  • 单个参数
    mybatis不会做特殊处理,#{参数名} 取出参数

  • 多个参数
    mybatis会做特殊处理,多个参数会被封装成一个map,
    key:param1…paramN
    value: 对应的按照顺序传入的参数
    #{param1} 就是从map中获取指定的值

  • 命名参数(@param(“xxx”))
    明确指定封装参数时map的key ==》接口定义时,使用@param注解
    多个参数会被封装成一个map
    key:使用@param注解指定的值
    value:参数值
    #{key} 就是从map中获取指定的值

public Employee getEmpByIdAndLastName(@Param("id") int id, @Param("lastName") String lastName);

<select id="getEmpByIdAndLastName" resultType="employee">
   select id,last_name,email,gender from tbl_employee 
   where id = #{id} and last_name =#{lastName}
</select>
  • 实体类
    如果多个参数正好是我们业务逻辑的数据原型,可以之间传入pojo;#{属性名} 取出对应的值

  • Map
    如果多个参数不是业务模型中的数据,没有对应的pojo,为了方便,我们也可以传入map
    #{key} 取出对应的值

在这里插入图片描述
【补充】
参数值的获取
#{} :以预编译的形式,将参数设置到sql语句中,类似于jdbc的参数占位符,防止sql注入
${} : 取出的值直接拼装在sql语句中,会有安全问题

4、select 返回list和map

如果select返回list ,resultType 取得是 list 中的泛型
如果select返回map,resultType = “map”

5、resultMap

1)自定义结果映射规则:
<resultMap id="myemp" type="com.atguigu.mybatis.bean.Employee">
    <!--指定主键列的封装规则
    id 定义主键,底层会有优化
    column :指定哪一列
    property: 指定对应的javaBean属性
    -->
    <id column="id" property="id"></id>
    <result column="last_name" property="lastName"></result>
</resultMap>

<select id="getEmpById" resultMap="myemp">
    select * from tbl_employee where id = #{id}
</select>
2) 级联属性封装结果:
<resultMap id="myEmpDept" type="com.atguigu.mybatis.bean.Employee">
    <id column="id" property="id"></id>
    <result column="last_name" property="lastName"></result>
    <result column="gender" property="gender"></result>
    <result column="email" property="email"></result>
    <result column="did" property="dept.id"></result>
    <result column="dept_name" property="dept.deptName"></result>
</resultMap>

<select id="getEmpAndDept" resultMap="myEmpDept">
    select
    e.id id,
    e.last_name last_name,
    e.gender gender,
    e.email email,
    d.id did,
    d.dept_name dept_name
    from  tbl_employee e left join tbl_dept d
    on e.dept_id = d.id
    where e.dept_Id = 2
</select>

【注意】Employee中有一个Department对象
在这里插入图片描述
在这里插入图片描述

3) association定义关联对象封装规则:
<!--
    使用 association ,封装关联的单个对象
-->
<resultMap id="myEmpDept1" type="com.atguigu.mybatis.bean.Employee">
    <id column="id" property="id"></id>
    <result column="last_name" property="lastName"></result>
    <result column="gender" property="gender"></result>
    <result column="email" property="email"></result>

    <!-- association 可以指定联合的javaBean对象
         property : 指定哪个属性是联合的对象
         javaType : 指定这个属性对象的类型
    -->
    <association property="dept" javaType="com.atguigu.mybatis.bean.Department">
        <result column="did" property="id"></result>
        <result column="dept_name" property="deptName"></result>
    </association>
</resultMap>

<select id="getEmpAndDept" resultMap="myEmpDept1">
    select
    e.id id,
    e.last_name last_name,
    e.gender gender,
    e.email email,
    d.id did,
    d.dept_name dept_name
    from  tbl_employee e left join tbl_dept d
    on e.dept_id = d.id
    where e.dept_Id = #{id}
</select>
4) association分步查询

先准备好department对象的mapper和 xml文件
在这里插入图片描述
DepartmentMapper.xml

<select id="getDeptById" resultType="com.atguigu.mybatis.bean.Department">
   select id,dept_name deptName from tbl_dept where id =#{id}
</select>

EmployeeMapperPlus.xml

<!-- association 分步查询-->
<resultMap id="myEmpDept2" type="com.atguigu.mybatis.bean.Employee">
    <id column="id" property="id"></id>
    <result column="last_name" property="lastName"></result>
    <result column="gender" property="gender"></result>
    <result column="email" property="email"></result>

    <!-- association 可以指定联合的javaBean对象
         property : 指定哪个属性是联合的对象
         select: 调用目标的方法查询当前属性的值
         column: 将sql中的哪一列传入上述调用的方法
    -->
    <association property="dept" select="com.atguigu.mybatis.mapper.DepartmentMapper.getDeptById" column="dept_id">
    </association>
</resultMap>

<select id="getEmpAndDept" resultMap="myEmpDept2">
    select
    e.id id,
    e.last_name last_name,
    e.gender gender,
    e.email email,
    e.dept_id
    from  tbl_employee e 
    where e.dept_Id = #{id}
</select>
5) 分步查询&延迟加载

只有在真正用到关联对象时,才会进行第二次的分布查询
mybatis配置文件中,添加配置

<settings>
   <setting name="lazyLoadingEnabled" value="true"/>
   <setting name="aggressiveLazyLoading" value="false"/>
</settings>

在这里插入图片描述

6)collection定义关联集合封装规则
<resultMap id="myDept" type="com.atguigu.mybatis.bean.Department">
   <id column="did" property="id"></id>
   <result column="dept_name" property="deptName"></result>

   <!--
      collection 定义集合类型属性的封装规则
      ofType: 集合中元素的类型
   -->
   <collection property="emps" ofType="com.atguigu.mybatis.bean.Employee">
      <!--定义集合中元素的封装规则-->
      <id column="eid" property="id"></id>
      <result column="last_name" property="lastName"></result>
      <result column="email" property="email"></result>
      <result column="gender" property="gender"></result>
   </collection>
</resultMap>

<select id="getgetDeptByIdPlus" resultMap="myDept">
   select 
   d.id did,
   d.dept_name dept_name,
   e.id eid,
   e.last_name last_name,
   e.email email,
   e.gender gender
   from tbl_dept d
   left join tbl_employee e
   on d.id =e.dept_id
   where d.id =#{id}
</select>
7)collection分步查询和延迟加载
<!--collection 分步查询-->
<resultMap id="myDeptStep" type="com.atguigu.mybatis.bean.Department">
   <id column="id" property="id"></id>
   <result column="dept_name" property="deptName"></result>
   <collection property="emps" select="com.atguigu.mybatis.mapper.EmployeeMapper.getEmpsByDeptId" column="id">

   </collection>
</resultMap>

<select id="getgetDeptByIdStep" resultMap="myDeptStep">
   select id,dept_name from tbl_dept where id =#{id}
</select>

下图中sql打印了两次,可见确实是分步查询
在这里插入图片描述
【扩展】:分步查询select中方法,如果要传多列的值:
将多列的值封装成map传递
column = “{k1= column1}”

fetchType ="lazy":表示延迟加载
	-lazy :延迟加载
	-eager: 立即查询
<collection property="emps" select="com.atguigu.mybatis.mapper.EmployeeMapper.getEmpsByDeptId" column="id" fetchType="lazy">

</collection>

四、Mybatis- 动态sql

1、if标签

<select id="getEmpsByConditionIf" resultType="com.atguigu.mybatis.bean.Employee">
   select * from tbl_employee
   where 1=1
   <if test="id!=null">
      and id = #{id}
   </if>
   <if test="lastName!=null and lastName !=''">
      and last_name like '%${lastName}%'
   </if>
   <if test="email!=null">
      and email like  '%${email}%'
   </if>
   <if test="gender==0 or gender == 1">
      and gender = #{gender}
   </if>
</select>

2、where标签

去除动态sql中多余的and 和 or

<select id="getEmpsByConditionIf" resultType="com.atguigu.mybatis.bean.Employee">
   select * from tbl_employee
   <where>
      <if test="id!=null">
         and id = #{id}
      </if>
      <if test="lastName!=null and lastName !=''">
         and last_name like '%${lastName}%'
      </if>
      <if test="email!=null">
         and email like  '%${email}%'
      </if>
      <if test="gender==0 or gender == 1">
         and gender = #{gender}
      </if>
   </where>
</select>

3、trim 字符串截取

<select id="getEmpsByConditionTrim" resultType="com.atguigu.mybatis.bean.Employee">
   select * from tbl_employee
   <!--
      后面多出的and or where 标签不能解决
      trim标签体中是整个字符串拼拼接后的结果

      prefix:给拼串后的字符串加一个前缀
      prefixOverrides="" : 前缀覆盖 去掉整个字符串前面多余的字符串
      suffixOverrides="" : 后缀覆盖 去掉整个字符串后面多余的字符串
   -->
   <trim prefix="where" suffixOverrides="and">
      <if test="id!=null">
         id = #{id} and
      </if>
      <if test="lastName!=null and lastName !=''">
         last_name like '%${lastName}%' and
      </if>
      <if test="email!=null">
         email like  '%${email}%' and
      </if>
      <if test="gender==0 or gender == 1">
         gender = #{gender} and
      </if>
   </trim>
</select>

4、choose when otherwise

<select id="getEmpsByConditionChoose" resultType="com.atguigu.mybatis.bean.Employee">
   select * from tbl_employee
   <where>
      <choose>
         <when test="id!=null">
            and id = #{id}
         </when>
         <when test="lastName!=null and lastName !=''">
            and last_name like '%${lastName}%'
         </when>
         <otherwise>
            and gender = 1
         </otherwise>
      </choose>
   </where>
</select>

5、set

用来更新数据库中的字段

<update id="updateEmp">
	 	<!-- Set标签的使用 -->
	 	update tbl_employee 
		<set>
			<if test="lastName!=null">
				last_name=#{lastName},
			</if>
			<if test="email!=null">
				email=#{email},
			</if>
			<if test="gender!=null">
				gender=#{gender}
			</if>
		</set>
		where id=#{id} 
<!-- 	

6、foreach

<select id="getEmpsByConditionForeach" resultType="com.atguigu.mybatis.bean.Employee">
	 	select * from tbl_employee
	 	<!--
	 		collection:指定要遍历的集合:
	 			list类型的参数会特殊处理封装在map中,map的key就叫list
	 		item:将当前遍历出的元素赋值给指定的变量
	 		separator:每个元素之间的分隔符
	 		open:遍历出所有结果拼接一个开始的字符
	 		close:遍历出所有结果拼接一个结束的字符
	 		index:索引。遍历list的时候是index就是索引,item就是当前值
	 				      遍历map的时候index表示的就是map的key,item就是map的值
	 		
	 		#{变量名}就能取出变量的值也就是当前遍历出的元素
	 	  -->
	 	<foreach collection="ids" item="item_id" separator=","
	 		open="where id in(" close=")">
	 		#{item_id}
	 	</foreach>
	 </select>

mysql foreach 批量保存

<!--public void addEmps(@Param("emps")List<Employee> emps);  -->
<!--MySQL下批量保存:可以foreach遍历   mysql支持values(),(),()语法-->
<insert id="addEmps">
	insert into tbl_employee(last_name,email,gender,dept_id)	
	values
	<foreach collection="emps" item="emp" separator=",">
		(#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
	</foreach>
</insert>

7、内置参数_parameter&_databaseId

两个内置参数:
不只是方法传递过来的参数可以被用来判断,取值。。。
mybatis默认还有两个内置参数:

_parameter:代表整个参数
	 		单个参数:_parameter就是这个参数
	 		多个参数:参数会被封装为一个map;_parameter就是代表这个map

_databaseId:如果配置了databaseIdProvider标签。
	 		_databaseId就是代表当前数据库的别名

8、可重用sql片段

定义sql片段:

<sql id="sqlColumn">
   id,last_name,email,gender
</sql>

引用sql片段:

<select id="getEmpsByConditionChoose" resultType="com.atguigu.mybatis.bean.Employee">
   select
   <include refid="sqlColumn"></include>
   from tbl_employee
   <where>
      <choose>
         <when test="id!=null">
            and id = #{id}
         </when>
         <when test="lastName!=null and lastName !=''">
            and last_name like '%${lastName}%'
         </when>
         <otherwise>
            and gender = 1
         </otherwise>
      </choose>
   </where>
</select>

五、Mybatis- 缓存机制

mybatis包含一个非常强大的查询缓存特性,他可以非常方便的配置和定制,缓存可以极大的提高查询效率

mybatis系统中提供了两级缓存:

  • 一级缓存
  • 二级缓存

1、一级缓存体验

@Test
public void testFirstCache() throws IOException {
    SqlSession sqlSession = getSqlSessionFactory().openSession();

    EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
    Employee emp = mapper.getEmpById(1);
    System.out.println(emp);

    Employee emp1 = mapper.getEmpById(1);
    System.out.println(emp1);
    System.out.println(emp1==emp);
}

在这里插入图片描述
【结论】 由上面的结果可以看出
两次查询,但是只打印了一次sql语句,说明第二次查询是从缓存中直接取出的结果,而不是再一次执行查询操作

2、一级缓存失效的四种情况

一级缓存的失效情况(没有使用到当前一级缓存的情况,也就是,还需要向数据库发出查询)
1、sqlSession不同
2、sqlSession相同,但是查询条件不同
3、sqlSession相同,两次查询之间执行了增删改操作(这次操作可能对之前的数据有影响)
4、sqlSession相同,手动清除了一级缓存

3、二级缓存介绍

二级缓存(全局缓存) namespace级别的缓存,一个namespace对应一个二级缓存
工作机制:
1、一个会话,查询一条数据,这个数据就被放在当前会话的一级缓存中
2、如果会话关闭,一级会话中的数据被保存到二级缓存中
3、不同namespace查询的数据会被放在自己对应的map(二级缓存)中

如何使用二级缓存
1、配置文件中开启二级缓存

<setting name="cacheEnabled" value="true"/>

2、mapper.xml文件中配置二级缓存
3、二级缓存需要实体类实现序列化接口

4、缓存有关的设置以及属性

1)cacheEnabled = false : 关闭二级缓存(一级缓存一直是可用的)
2) 每个select标签都有一个 useCache = true
//useCache = false 禁用二级缓存(对一级缓存没有影响)
3)每个增删改标签具有属性 :flushCache =true
(即执行增删改后,一级缓存就清空了,二级缓存也会被清空),查询标签也有flushcache属性,只不过默认为false

4)sqlSession.clear() 只是清除当前session的一级缓存

5、缓存原理图示

sqlSession.clear() 只是清除当前session的一级缓存

6、第三方缓存整合原理

一级缓存、二级缓存是在内存中,下面演示mybatis整合ehcache作为二级缓存
1)导入ehcache的jar包和mybatis与ehcache的整合包 (引入依赖)

<dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-ehcache</artifactId>
    <version>1.2.1</version>
  </dependency>

2)在mapper.xml中配置二级缓存

<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

type => 指定缓存的类型

带一些属性的二级缓存

<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
    <property name="timeToIdleSeconds" value="3600"/><!--1 hour-->
    <property name="timeToLiveSeconds" value="3600"/><!--1 hour-->
    <property name="maxEntriesLocalHeap" value="1000"/>
    <property name="maxEntriesLocalDisk" value="10000000"/>
    <property name="memoryStoreEvictionPolicy" value="LRU"/>
  </cache>

3)在类路径下添加 ehcache 配置文件 ehcache.xml

<?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:\44\ehcache" />
 
 <defaultCache 
   maxElementsInMemory="1" 
   maxElementsOnDisk="10000000"
   eternal="false" 
   overflowToDisk="true" 
   timeToIdleSeconds="120"
   timeToLiveSeconds="120" 
   diskExpiryThreadIntervalSeconds="120"
   memoryStoreEvictionPolicy="LRU">
 </defaultCache>
</ehcache>
 
<!-- 
属性说明:
l diskStore:指定数据在磁盘中的存储位置。
l defaultCache:当借助CacheManager.add("demoCache")创建Cache时,EhCache便会采用<defalutCache/>指定的的管理策略
 
以下属性是必须的:
l maxElementsInMemory - 在内存中缓存的element的最大数目 
l maxElementsOnDisk - 在磁盘上缓存的element的最大数目,若是0表示无穷大
l eternal - 设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断
l overflowToDisk - 设定当内存缓存溢出的时候是否将过期的element缓存到磁盘上
 
以下属性是可选的:
l timeToIdleSeconds - 当缓存在EhCache中的数据前后两次访问的时间超过timeToIdleSeconds的属性取值时,这些数据便会删除,默认值是0,也就是可闲置时间无穷大
l timeToLiveSeconds - 缓存element的有效生命期,默认是0.,也就是element存活时间无穷大
 diskSpoolBufferSizeMB 这个参数设置DiskStore(磁盘缓存)的缓存区大小.默认是30MB.每个Cache都应该有自己的一个缓冲区.
l diskPersistent - 在VM重启的时候是否启用磁盘保存EhCache中的数据,默认是false。
l diskExpiryThreadIntervalSeconds - 磁盘缓存的清理线程运行间隔,默认是120秒。每个120s,相应的线程会进行一次EhCache中数据的清理工作
l memoryStoreEvictionPolicy - 当内存缓存达到最大,有新的element加入的时候, 移除缓存中element的策略。默认是LRU(最近最少使用),可选的有LFU(最不常使用)和FIFO(先进先出)
 -->
  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值