Question

I have no idea why my example app not use 2nd level cache in the second hibernate query.

In log i can see after query:

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

But in the next query Hibernate repeat the query.

My app implementation:

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>

The controller

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

}

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

}

Hibernate properties

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

Debug log:

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
Was it helpful?

Solution

It seems that actorService.getActorById is implemented with a custom query, instead of using entityManager.find(1, Actor.class) or session.load(Actor.class, 1).

The query cache is off, which means that the result of such query will not be cached.

Custom queries don't trigger the second level cache directly. They will hit first the query cache or the database and the ids returned are used to hit the second level cache.

In order to fix this, you can implement actorService.getActorById in terms of one of those two methods, which hit the second level cache. Or turn on the query cache:

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

And then make the query cacheable with setCacheable(true) in case of criteria, or like this if it's a named query:

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

There aren't that many cases where we would really want to use one of the two caches, they really go together in most cases.

OTHER TIPS

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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top