【问题标题】:Spring, and Hibernate 2nd level with EhcacheSpring,以及带有 Ehcache 的 Hibernate 2 级
【发布时间】:2014-04-02 18:37:28
【问题描述】:

我不知道为什么我的示例应用程序没有在第二个休眠查询中使用二级缓存。

在日志中我可以在查询后看到:

04-02-2014 08:28:10,869 PM DEBUG TwoPhaseLoad:194 - Adding entity to second-level cache: [com.pjcom.pjcomspringehcache.model.entity.Actor#1]

但是在下一个查询 Hibernate 重复查询。

我的应用实现:

pom.xml

<properties>
        <spring-version>4.0.3.RELEASE</spring-version>
        <hibernate-version>4.3.4.Final</hibernate-version>
        <org.slf4j-version>1.5.10</org.slf4j-version>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

<dependencies>

    <!-- SPRING -->

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

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</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-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-webmvc</artifactId>
        <version>4.0.3.RELEASE</version>
    </dependency>

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

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

    <!-- END SPRING -->

    <!-- HIBERNATE -->

    <dependency>
        <groupId>org.hibernate.common</groupId>
        <artifactId>hibernate-commons-annotations</artifactId>
        <version>4.0.4.Final</version>
    </dependency>

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

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

    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.1-api</artifactId>
        <version>1.0.0.Final</version>
    </dependency>

    <!-- END HIBERNATE -->

    <!-- EHCACHE -->

    <dependency>
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache</artifactId>
        <version>2.8.1</version>
    </dependency>

    <!-- END EHCACHE -->

    <!-- MYSQL -->

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.30</version>
    </dependency>

    <!-- END MYSQL -->

    <!-- SLF4J -->

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.6</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        <version>1.7.6</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.6</version>
        <scope>runtime</scope>
    </dependency>

    <!-- END SLF4J -->      

    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-web-api</artifactId>
        <version>6.0</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

控制器

@Controller
public class MainController implements ToCache {

    @Autowired
    private ActorService actorService;

    @RequestMapping(value = {"/", "/index"})
    public String showHome(HttpServletRequest request) {

        request.setAttribute("now", new Date());
        request.setAttribute("tmp", System.getProperty("java.io.tmpdir"));

        System.out.println("First Quering:");
        Actor actor1 = this.actorService.getActorById(1);
        System.out.println("Actor1: " + actor1.getFirstName());

        System.out.println("Second Quering:");
        Actor actor2 = this.actorService.getActorById(1);
        System.out.println("Actor2: " + actor2.getFirstName());
        request.setAttribute("actor", actor2);

        return "index";
    }

    @RequestMapping("/update")
    public String updateActor(HttpServletRequest request) {

        this.actorService.updateActorUpdateById(1);

        return "redirect:/index";
    }

}

实体pojo

@Entity
@Table(name = "actor")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Actor implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "actor_id")
    private int actorId;
    @Column(name = "first_name")
    private String firstName;
    @Column(name = "last_name")
    private String lastName;
    @Type(type="timestamp")
    @Column(name = "last_update")
    private Timestamp lastUpdate;

    public int getActorId() {
        return actorId;
    }

    public void setActorId(int actorId) {
        this.actorId = actorId;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Timestamp getLastUpdate() {
        return lastUpdate;
    }

    public void setLastUpdate(Timestamp lastUpdate) {
        this.lastUpdate = lastUpdate;
    }

}

休眠属性

<property name="hibernateProperties">
        <props>
            <!-- Esta propiedad establece que solo se actualiza una tabla cuando haya cambios -->
            <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
            <!-- Esta propiedad establece el lenguaje de la base de datos, en este caso MySQL -->
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>
            <!--
            Esta propiedad sirve para aplicar un alias en nuestras consultas.
            Si creamos una consulta con un true, nosotros al aplicarle un alias 'T',
            con poner T automaticamente lo recombertira Hibernate en la consulta final
            por nosotros.
            -->
            <prop key="hibernate.query.substitutions">${hibernate.query.substitutions}</prop>
            <!-- Sirve para desactivar el debug de las consultas en la consola. -->
            <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>

            <!-- CACHE CONFIGURATION -->

            <!-- Path al fichero de configuracion de Ehcache -->
            <prop key="hibernate.cache.provider_configuration_file_resource_path">ehcache.xml</prop>
            <!-- Habilita la cache de segundo nivel -->
            <prop key="hibernate.cache.use_second_level_cache">true</prop>
            <!-- Habilita la cache de querys -->
            <prop key="hibernate.cache.use_query_cache">false</prop>
            <!-- Establece el motor de cache de segundo nivel -->
            <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
            <!--<prop key="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</prop>-->

            <!-- END CACHE CONFIGURATION -->

        </props>
</property>

Ehcache.xml

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" 
         updateCheck="true" 
         monitoring="autodetect" 
         dynamicConfig="true"
         maxBytesLocalHeap="150M">

    <diskStore path="java.io.tmpdir"/>    

    <defaultCache eternal="false"
                  timeToIdleSeconds="10"
                  timeToLiveSeconds="10"
                  overflowToDisk="true"
                  maxElementsOnDisk="1000" />

    <cache name="com.pjcom.pjcomspringehcache.model.entity.Actor"
           eternal="false"
           timeToIdleSeconds="30"
           timeToLiveSeconds="30"
           overflowToDisk="true"
           maxElementsOnDisk="1000" />

</ehcache>

调试日志:

04-02-2014 08:28:10,585 PM DEBUG DispatcherServlet:838 - DispatcherServlet with name 'sehcache' processing GET request for [/pjcomspringehcache/]
04-02-2014 08:28:10,585 PM DEBUG RequestMappingHandlerMapping:246 - Looking up handler method for path /
04-02-2014 08:28:10,585 PM DEBUG RequestMappingHandlerMapping:251 - Returning handler method [public java.lang.String com.pjcom.pjcomspringehcache.MainController.showHome(javax.servlet.http.HttpServletRequest)]
04-02-2014 08:28:10,586 PM DEBUG DefaultListableBeanFactory:249 - Returning cached instance of singleton bean 'mainController'
04-02-2014 08:28:10,586 PM DEBUG DispatcherServlet:925 - Last-Modified value for [/pjcomspringehcache/] is: -1
First Quering:
04-02-2014 08:28:10,586 PM DEBUG DefaultListableBeanFactory:249 - Returning cached instance of singleton bean 'transactionManager'
04-02-2014 08:28:10,586 PM DEBUG HibernateTransactionManager:367 - Creating new transaction with name [com.pjcom.pjcomspringehcache.service.impl.ActorServiceImpl.getActorById]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
04-02-2014 08:28:10,586 PM DEBUG HibernateTransactionManager:417 - Opened new Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=org.hibernate.engine.spi.ExecutableList@20f3d96a updates=org.hibernate.engine.spi.ExecutableList@6dae294 deletions=org.hibernate.engine.spi.ExecutableList@1119fd45 orphanRemovals=org.hibernate.engine.spi.ExecutableList@7eda981d collectionCreations=org.hibernate.engine.spi.ExecutableList@40dc2625 collectionRemovals=org.hibernate.engine.spi.ExecutableList@1143a2e8 collectionUpdates=org.hibernate.engine.spi.ExecutableList@4f6e8650 collectionQueuedOps=org.hibernate.engine.spi.ExecutableList@65def5d0 unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])] for Hibernate transaction
04-02-2014 08:28:10,586 PM DEBUG HibernateTransactionManager:427 - Preparing JDBC Connection of Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=org.hibernate.engine.spi.ExecutableList@20f3d96a updates=org.hibernate.engine.spi.ExecutableList@6dae294 deletions=org.hibernate.engine.spi.ExecutableList@1119fd45 orphanRemovals=org.hibernate.engine.spi.ExecutableList@7eda981d collectionCreations=org.hibernate.engine.spi.ExecutableList@40dc2625 collectionRemovals=org.hibernate.engine.spi.ExecutableList@1143a2e8 collectionUpdates=org.hibernate.engine.spi.ExecutableList@4f6e8650 collectionQueuedOps=org.hibernate.engine.spi.ExecutableList@65def5d0 unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])]
04-02-2014 08:28:10,586 PM DEBUG LogicalConnectionImpl:226 - Obtaining JDBC connection
04-02-2014 08:28:10,587 PM DEBUG DriverManagerDataSource:142 - Creating new JDBC DriverManager Connection to [jdbc:mysql://localhost:3306/sakila]
04-02-2014 08:28:10,590 PM DEBUG LogicalConnectionImpl:232 - Obtained JDBC connection
04-02-2014 08:28:10,590 PM DEBUG DataSourceUtils:153 - Setting JDBC Connection [com.mysql.jdbc.JDBC4Connection@35dbba34] read-only
04-02-2014 08:28:10,591 PM DEBUG AbstractTransactionImpl:160 - begin
04-02-2014 08:28:10,591 PM DEBUG JdbcTransaction:69 - initial autocommit status: true
04-02-2014 08:28:10,591 PM DEBUG JdbcTransaction:71 - disabling autocommit
04-02-2014 08:28:10,591 PM DEBUG HibernateTransactionManager:488 - Exposing Hibernate transaction as JDBC transaction [com.mysql.jdbc.JDBC4Connection@35dbba34]
04-02-2014 08:28:10,591 PM DEBUG SQL:109 - select this_.actor_id as actor_id1_0_0_, this_.first_name as first_na2_0_0_, this_.last_name as last_nam3_0_0_, this_.last_update as last_upd4_0_0_ from actor this_ where this_.actor_id=?
Hibernate: select this_.actor_id as actor_id1_0_0_, this_.first_name as first_na2_0_0_, this_.last_name as last_nam3_0_0_, this_.last_update as last_upd4_0_0_ from actor this_ where this_.actor_id=?
04-02-2014 08:28:10,592 PM DEBUG Loader:951 - Result set row: 0
04-02-2014 08:28:10,592 PM DEBUG Loader:1485 - Result row: EntityKey[com.pjcom.pjcomspringehcache.model.entity.Actor#1]
04-02-2014 08:28:10,593 PM DEBUG TwoPhaseLoad:160 - Resolving associations for [com.pjcom.pjcomspringehcache.model.entity.Actor#1]
04-02-2014 08:28:10,804 PM DEBUG TwoPhaseLoad:194 - Adding entity to second-level cache: [com.pjcom.pjcomspringehcache.model.entity.Actor#1]
04-02-2014 08:28:10,804 PM DEBUG TwoPhaseLoad:286 - Done materializing entity [com.pjcom.pjcomspringehcache.model.entity.Actor#1]
04-02-2014 08:28:10,806 PM DEBUG HibernateTransactionManager:755 - Initiating transaction commit
04-02-2014 08:28:10,806 PM DEBUG HibernateTransactionManager:551 - Committing Hibernate transaction on Session [SessionImpl(PersistenceContext[entityKeys=[EntityKey[com.pjcom.pjcomspringehcache.model.entity.Actor#1]],collectionKeys=[]];ActionQueue[insertions=org.hibernate.engine.spi.ExecutableList@20f3d96a updates=org.hibernate.engine.spi.ExecutableList@6dae294 deletions=org.hibernate.engine.spi.ExecutableList@1119fd45 orphanRemovals=org.hibernate.engine.spi.ExecutableList@7eda981d collectionCreations=org.hibernate.engine.spi.ExecutableList@40dc2625 collectionRemovals=org.hibernate.engine.spi.ExecutableList@1143a2e8 collectionUpdates=org.hibernate.engine.spi.ExecutableList@4f6e8650 collectionQueuedOps=org.hibernate.engine.spi.ExecutableList@65def5d0 unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])]
04-02-2014 08:28:10,806 PM DEBUG AbstractTransactionImpl:175 - committing
04-02-2014 08:28:10,807 PM DEBUG JdbcTransaction:113 - committed JDBC Connection
04-02-2014 08:28:10,807 PM DEBUG JdbcTransaction:126 - re-enabling autocommit
04-02-2014 08:28:10,807 PM DEBUG DataSourceUtils:222 - Resetting read-only flag of JDBC Connection [com.mysql.jdbc.JDBC4Connection@35dbba34]
04-02-2014 08:28:10,808 PM DEBUG HibernateTransactionManager:633 - Closing Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[EntityKey[com.pjcom.pjcomspringehcache.model.entity.Actor#1]],collectionKeys=[]];ActionQueue[insertions=org.hibernate.engine.spi.ExecutableList@20f3d96a updates=org.hibernate.engine.spi.ExecutableList@6dae294 deletions=org.hibernate.engine.spi.ExecutableList@1119fd45 orphanRemovals=org.hibernate.engine.spi.ExecutableList@7eda981d collectionCreations=org.hibernate.engine.spi.ExecutableList@40dc2625 collectionRemovals=org.hibernate.engine.spi.ExecutableList@1143a2e8 collectionUpdates=org.hibernate.engine.spi.ExecutableList@4f6e8650 collectionQueuedOps=org.hibernate.engine.spi.ExecutableList@65def5d0 unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])] after transaction
04-02-2014 08:28:10,808 PM DEBUG LogicalConnectionImpl:246 - Releasing JDBC connection
04-02-2014 08:28:10,809 PM DEBUG LogicalConnectionImpl:264 - Released JDBC connection
Actor1: PENELOPE
Second Quering:
04-02-2014 08:28:10,809 PM DEBUG DefaultListableBeanFactory:249 - Returning cached instance of singleton bean 'transactionManager'
04-02-2014 08:28:10,809 PM DEBUG HibernateTransactionManager:367 - Creating new transaction with name [com.pjcom.pjcomspringehcache.service.impl.ActorServiceImpl.getActorById]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
04-02-2014 08:28:10,810 PM DEBUG HibernateTransactionManager:417 - Opened new Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=org.hibernate.engine.spi.ExecutableList@3a4aa3fe updates=org.hibernate.engine.spi.ExecutableList@4866470f deletions=org.hibernate.engine.spi.ExecutableList@768e924d orphanRemovals=org.hibernate.engine.spi.ExecutableList@7d80db9b collectionCreations=org.hibernate.engine.spi.ExecutableList@123ad286 collectionRemovals=org.hibernate.engine.spi.ExecutableList@689ea1f1 collectionUpdates=org.hibernate.engine.spi.ExecutableList@6a804a55 collectionQueuedOps=org.hibernate.engine.spi.ExecutableList@11a7189d unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])] for Hibernate transaction
04-02-2014 08:28:10,810 PM DEBUG HibernateTransactionManager:427 - Preparing JDBC Connection of Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=org.hibernate.engine.spi.ExecutableList@3a4aa3fe updates=org.hibernate.engine.spi.ExecutableList@4866470f deletions=org.hibernate.engine.spi.ExecutableList@768e924d orphanRemovals=org.hibernate.engine.spi.ExecutableList@7d80db9b collectionCreations=org.hibernate.engine.spi.ExecutableList@123ad286 collectionRemovals=org.hibernate.engine.spi.ExecutableList@689ea1f1 collectionUpdates=org.hibernate.engine.spi.ExecutableList@6a804a55 collectionQueuedOps=org.hibernate.engine.spi.ExecutableList@11a7189d unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])]
04-02-2014 08:28:10,857 PM DEBUG LogicalConnectionImpl:226 - Obtaining JDBC connection
04-02-2014 08:28:10,857 PM DEBUG DriverManagerDataSource:142 - Creating new JDBC DriverManager Connection to [jdbc:mysql://localhost:3306/sakila]
04-02-2014 08:28:10,864 PM DEBUG LogicalConnectionImpl:232 - Obtained JDBC connection
04-02-2014 08:28:10,865 PM DEBUG DataSourceUtils:153 - Setting JDBC Connection [com.mysql.jdbc.JDBC4Connection@36759eb4] read-only
04-02-2014 08:28:10,865 PM DEBUG AbstractTransactionImpl:160 - begin
04-02-2014 08:28:10,865 PM DEBUG JdbcTransaction:69 - initial autocommit status: true
04-02-2014 08:28:10,865 PM DEBUG JdbcTransaction:71 - disabling autocommit
04-02-2014 08:28:10,866 PM DEBUG HibernateTransactionManager:488 - Exposing Hibernate transaction as JDBC transaction [com.mysql.jdbc.JDBC4Connection@36759eb4]
04-02-2014 08:28:10,867 PM DEBUG SQL:109 - select this_.actor_id as actor_id1_0_0_, this_.first_name as first_na2_0_0_, this_.last_name as last_nam3_0_0_, this_.last_update as last_upd4_0_0_ from actor this_ where this_.actor_id=?
Hibernate: select this_.actor_id as actor_id1_0_0_, this_.first_name as first_na2_0_0_, this_.last_name as last_nam3_0_0_, this_.last_update as last_upd4_0_0_ from actor this_ where this_.actor_id=?
04-02-2014 08:28:10,868 PM DEBUG Loader:951 - Result set row: 0
04-02-2014 08:28:10,868 PM DEBUG Loader:1485 - Result row: EntityKey[com.pjcom.pjcomspringehcache.model.entity.Actor#1]
04-02-2014 08:28:10,869 PM DEBUG TwoPhaseLoad:160 - Resolving associations for [com.pjcom.pjcomspringehcache.model.entity.Actor#1]
04-02-2014 08:28:10,869 PM DEBUG TwoPhaseLoad:194 - Adding entity to second-level cache: [com.pjcom.pjcomspringehcache.model.entity.Actor#1]
04-02-2014 08:28:10,870 PM DEBUG TwoPhaseLoad:286 - Done materializing entity [com.pjcom.pjcomspringehcache.model.entity.Actor#1]
04-02-2014 08:28:10,870 PM DEBUG HibernateTransactionManager:755 - Initiating transaction commit
04-02-2014 08:28:10,871 PM DEBUG HibernateTransactionManager:551 - Committing Hibernate transaction on Session [SessionImpl(PersistenceContext[entityKeys=[EntityKey[com.pjcom.pjcomspringehcache.model.entity.Actor#1]],collectionKeys=[]];ActionQueue[insertions=org.hibernate.engine.spi.ExecutableList@3a4aa3fe updates=org.hibernate.engine.spi.ExecutableList@4866470f deletions=org.hibernate.engine.spi.ExecutableList@768e924d orphanRemovals=org.hibernate.engine.spi.ExecutableList@7d80db9b collectionCreations=org.hibernate.engine.spi.ExecutableList@123ad286 collectionRemovals=org.hibernate.engine.spi.ExecutableList@689ea1f1 collectionUpdates=org.hibernate.engine.spi.ExecutableList@6a804a55 collectionQueuedOps=org.hibernate.engine.spi.ExecutableList@11a7189d unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])]
04-02-2014 08:28:10,871 PM DEBUG AbstractTransactionImpl:175 - committing
04-02-2014 08:28:10,871 PM DEBUG JdbcTransaction:113 - committed JDBC Connection
04-02-2014 08:28:10,872 PM DEBUG JdbcTransaction:126 - re-enabling autocommit
04-02-2014 08:28:10,872 PM DEBUG DataSourceUtils:222 - Resetting read-only flag of JDBC Connection [com.mysql.jdbc.JDBC4Connection@36759eb4]
04-02-2014 08:28:10,873 PM DEBUG HibernateTransactionManager:633 - Closing Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[EntityKey[com.pjcom.pjcomspringehcache.model.entity.Actor#1]],collectionKeys=[]];ActionQueue[insertions=org.hibernate.engine.spi.ExecutableList@3a4aa3fe updates=org.hibernate.engine.spi.ExecutableList@4866470f deletions=org.hibernate.engine.spi.ExecutableList@768e924d orphanRemovals=org.hibernate.engine.spi.ExecutableList@7d80db9b collectionCreations=org.hibernate.engine.spi.ExecutableList@123ad286 collectionRemovals=org.hibernate.engine.spi.ExecutableList@689ea1f1 collectionUpdates=org.hibernate.engine.spi.ExecutableList@6a804a55 collectionQueuedOps=org.hibernate.engine.spi.ExecutableList@11a7189d unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])] after transaction
04-02-2014 08:28:10,873 PM DEBUG LogicalConnectionImpl:246 - Releasing JDBC connection
04-02-2014 08:28:10,873 PM DEBUG LogicalConnectionImpl:264 - Released JDBC connection
Actor2: PENELOPE
04-02-2014 08:28:10,908 PM DEBUG DispatcherServlet:1214 - Rendering view [org.springframework.web.servlet.view.InternalResourceView: name 'index'; URL [/WEB-INF/view/index.jsp]] in DispatcherServlet with name 'sehcache'
04-02-2014 08:28:10,908 PM DEBUG InternalResourceView:207 - Forwarding to resource [/WEB-INF/view/index.jsp] in InternalResourceView 'index'
04-02-2014 08:28:10,913 PM DEBUG DispatcherServlet:991 - Successfully completed request

【问题讨论】:

  • 我已经发布了一个可能的回复,如果它不起作用,您可以使用hibernate.cache.use_sql_comments=true 发布日志吗?看看这篇我写的关于二级和查询缓存的陷阱blog.jhades.org/…

标签: java spring hibernate ehcache


【解决方案1】:

似乎actorService.getActorById 是通过自定义查询实现的,而不是使用entityManager.find(1, Actor.class)session.load(Actor.class, 1)

查询缓存关闭,表示该查询的结果不会被缓存。

自定义查询不会直接触发二级缓存。他们将首先命中查询缓存或数据库,返回的 id 用于命中二级缓存。

为了解决这个问题,您可以使用这两种方法中的一种来实现actorService.getActorById,它会命中二级缓存。或者开启查询缓存:

 <prop key="hibernate.cache.use_query_cache">true</prop>

然后在满足条件的情况下使用setCacheable(true) 使查询可缓存,如果是命名查询,则像这样:

@NamedQuery(name="account.queryName",
   query="select acct from Account ...",
   hints={
       @QueryHint(name="org.hibernate.cacheable",
       value="true")
   }     
})

我们真正想要使用两个缓存之一的情况并不多,大多数情况下它们确实是一起使用的。

【讨论】:

  • 您的帖子非常适合我,我从中学到了很多。谢谢。
【解决方案2】:
You need to check few things to implement this.

Firstly, what is the hibernate version, you are using 3.2 or 3.3

For 3.2 and below
<property key="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.region.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</property>

For 3.3 and above
<property key="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</property>


You can also enable query caching. To do so configure it in your hbm.xml:
<property key="hibernate.cache.use_query_cache">true</property>

Other way to do this is:
sessionFactory.getCurrentSession().createQuery("...").setCacheable(true).list();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-23
    • 2012-12-12
    • 2015-11-26
    • 1970-01-01
    • 2021-01-20
    • 2011-02-24
    • 1970-01-01
    • 2019-10-03
    相关资源
    最近更新 更多