I'm trying to figure out how I can get the standardized JPA 2.0 2nd level cache to work. The code is working when I use the @org.hibernate.annotations.Cache annotation on my entity so ehcache configuration etc. is correct. Without this annotation the cache doesn't work at all.
My configuration is as follows:
Code:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="testPU" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/jpa_course"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.sharedCache.mode" value="ALL"/>
<property name="hibernate.archive.autodetection" value="class"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.cache.use_second_level_cache" value="true"/>
<property name="hibernate.cache.use_query_cache" value="false"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.EhCacheProvider"/>
</properties>
</persistence-unit>
My entity is annotated as follows (all tough that should be true on default anyway):
Code:
@Entity
@Cacheable(true)
public class Employee {
My test code creates a new entitymanager each time and uses a EntityManager.find to load the entity.
Code:
for (int i = 0; i < 10000; i++) {
em = emf.createEntityManager();
em.find(Employee.class, 1L);
em.close();
}
There is an Employee with id 1 in the database.
Each find will execute another select query however, so the cache is not working at all. If I add @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) to the entity, it works correctly. That should not be necessary in JPA 2 however.