springboot 2集成hibernate5及ehcache3

葛阳华
2023-12-01

1、配置pom文件

            <dependency>
				<groupId>org.hibernate</groupId>
				<artifactId>hibernate-jcache</artifactId>
				<version>${hibernate.version}</version>
			</dependency>

			<dependency>
				<groupId>org.ehcache</groupId>
				<artifactId>ehcache</artifactId>
				<version>3.8.1</version>
			</dependency>

2、配置application.yml文件

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://10.74.0.218/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&useSSL=false
    password: 123456
    username: root
    type: com.zaxxer.hikari.HikariDataSource
    hikari:
      connection-test-query: SELECT 1 FROM DUAL
      minimum-idle: 1
      maximum-pool-size: 5
  jpa:
    hibernate:
      ddl-auto: none
    properties:
      hibernate:
        show_sql: true
        format_sql: false
        dialect: org.hibernate.dialect.MySQL5Dialect
        current_session_context_class: org.springframework.orm.hibernate5.SpringSessionContext
        cache:
          use_second_level_cache: true
          use_query_cache: true
          region.factory_class: org.hibernate.cache.jcache.JCacheRegionFactory
        javax.cache:
          provider: org.ehcache.jsr107.EhcacheCachingProvider
          uri: classpath:ehcache.xml
      javax:
        persistence:
          sharedCache:
            mode: ENABLE_SELECTIVE

3、配置ehcache.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.ehcache.org/v3"
        xmlns:jsr107="http://www.ehcache.org/v3/jsr107"
        xsi:schemaLocation="
            http://www.ehcache.org/v3
            http://www.ehcache.org/schema/ehcache-core.xsd
            http://www.ehcache.org/v3/jsr107
            http://www.ehcache.org/schema/ehcache-107-ext.xsd">
  <!--指定缓存持久化目录-->
  <persistence directory="${java.io.tmpdir}/ehcache-data"/>

  <cache alias="default-query-results-region">
    <expiry>
      <tti unit="seconds">300</tti>
    </expiry>
    <heap>1024</heap>
  </cache>

  <cache alias="default-update-timestamps-region">
    <expiry>
      <none />
    </expiry>
    <heap>4096</heap>
  </cache>

  <cache alias="USER" uses-template="default">
    <expiry>
      <tti unit="seconds">300</tti>
    </expiry>
    <heap>1024</heap>
  </cache>

  <cache-template name="default">
    <expiry>
      <tti unit="seconds">300</tti>
    </expiry>
    <heap>1024</heap>
  </cache-template>

</config>

4、在hibernate中使用二级缓存

使用二级缓存的原则是只能在可以直接映射为实体的查询中使用。例如NamedQuery,基于hql的查询以及Criteria查询。

	        //NamedQuery或NamedNativeQuery
            this.getSessionFactory()
			   .getCurrentSession()
			   .createNamedQuery("NamedQuery")
			   .setCacheable(true)
			   .list();
        
           //基于hql的查询
           this.getSessionFactory()
			   .getCurrentSession()
			   .createQuery(hql,Entity.class)
			   .setCacheable(true)
			   .list();

 

 

 类似资料: