Bean cache
To enable bean caching we add the @Cache
annotation to the entity bean
type.
@Cache
@Entity
public class Customer {
...
}
Natural key
We use the naturalKey
attribute to define a natural unique key
that can be used.
Ebean will then automatically maintain a natural key lookup cache and use this with queries that use the natural key properties in where expressions.
@Cache(naturalKey = "email")
// Multiple properties make up the unique natural key
@Cache(naturalKey = {"store","sku"})
Used implicitly
If @Cache has been defined on the bean then Ebean will automatically try and use the L2 bean cache.
@Cache
@Entity
public class Country
// automatically use the cache
Country country = DB.find(Country.class,"NZ");
// references automatically use the cache too
Country countryRef = DB.reference(Country.class,"NZ");
// hit the country cache automatically via navigation
// ... and lazy loading
Customer customer = DB.find(Customer.class, 1);
Address billingAddress = customer.getBillingAddress();
Country c2 = billingAddress.getCountry();
Explicitly
We can explicitly specify to use the bean cache via query.setUseCache()
and for the
bean cache we can say when we do not want to use the cache.
// explicitly state we do not want to use the bean cache
Customer customer = DB.find(Customer.class)
.setUseCache(false)
.setId(7)
.findOne();
Near cache
To enable near caching when using ebean-redis set nearCache=true
. To enable near caching with
Hazelcast or Ignite we instead use their Hazelcast | Ignite specific configuration.
@Cache(nearCache=true)
@Entity
public class Country
With the above, when using ebean-redis a query hitting the bean cache will first try the in-process near cache and only hit Redis when the data isn't in the local near cache.