Using Hibernate second level cache with JBoss AS and WildFly

Annotations used for Caching entities

If you are using JBoss 6.x / 7.x or WildFly then you can use the JPA 2 annotation @javax.persistence.Cacheable which, used in conjunction with the shared-cache-mode, can be used to determine if the Entity should be cached or not.
The above example can be also rewritten as:

@Entity
@Cacheable
public class User {

@Id
@Column(name="key")
private String key;

@Column(name="name")
private String name;
. . . . .
}

If you are using JBoss 5.x, the annotation used for Caching entities is @org.hibernate.annotations.Cache . For example:

@Entity
@Cache (usage=CacheConcurrencyStrategy.TRANSACTIONAL)
public class Entity {

@Id
@Column(name="key")
private String key;

. . . . .
}

The CacheConcurrencyStrategy.TRANSACTIONAL provides support for Infinispan fully transactional JTA environment.  
If there are chances that your application data is read but never modified, you can apply the READ_ONLY CacheConcurrencyStrategy that does not evict data from the cache

Annotations used to cache Queries

The Query cache can be used to cache data from a query so that if the same query is issued again, it will not hit the database but return the cached value.
Note that the query cache does not cache the state of the actual entities in the result set; it caches only identifier values and results of value type.

Caching a query can be done by adding a @QueryHint annotation to a @NamedQuery, as shown in the following example:

@NamedQueries(
{
@NamedQuery(
name = "listUsers",
query = "FROM User c WHERE c.name = :name",
hints = { @QueryHint(name = "org.hibernate.cacheable", value =
"true") }  
)
})
public class User {

@Id
@Column(name="key")
private String key;

@Column(name="name")
private String name;

. . . . .
}

Follow us on Twitter