Reputation: 12481
We have JPA entities representing lookup values (states, country codes, etc). Methods that are called frequently to get List
s of these values are cached using the org.springframework.cache.annotation.Cacheable
annotation where appropriate.
We also have entities that have relationships with these lookup entities defined like:
@Entity
@Table(name = "Address")
public class AddressEntity {
// ...
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "STATE_CD", referencedColumnName = "CD")
@NotNull
private StateEntity state;
// ...
}
When we load one of these entities and then call the getter on the associated lookup, Hibernate hits the database again to load that value. We'd like to make it so when we have an address and we do a getState
on that address, we hit a local cache for that information. How can we do that with Hibernate/JPA?
// Get address:
Address address = addressRepo.findOne(addressId);
// Get the state - this causes an additional query to hit the database:
State state = address.getState();
Upvotes: 1
Views: 377
Reputation: 10716
The fetch type does not matter here. Hibernate's second-level cache behavior is to cache the ids of to-one association targets rather than the targets themselves.
Why not make StateEntity
itself @Cacheable
? It seems a very good candidate, as there should be (much) fewer instances of StateEntity
than AddressEntity
Upvotes: 1