Reputation: 187499
According to the Grails manual
As well as the ability to use Hibernate's second level cache to cache instances you can also cache collections (associations) of objects. For example:
class Person {
static hasMany = [addresses: Address]
static mapping = {
cache true
addresses cache: true
}
}
If we cache the association between a person and their addresses, then does it make sense to also cache the inverse relationship, e.g.
class Address {
static belongsTo = [person: Person]
static mapping = {
cache true
person cache: true // is this necessary?
}
}
Obviously it would only make sense to cache the inverse relationship if (in our application code) we navigate from Address to Person, but assuming the relationship is navigated in both directions, does it also need to be cached in both directions?
The previous question is about caching in the context of a 1:N relationship. If the relationship between the two is 1:1 instead, presumably the same caching behaviors could/shouid be specified? For example:
class Person {
static hasOne = [address: Address]
static mapping = {
cache true
address cache: true
}
}
class Address {
static belongsTo = [person: Person]
static mapping = {
cache true
person cache: true
}
}
If we have a N:N relationship between two objects, and we navigate the relationship in both directions, is the following the correct way to cache the associations:
class Person {
static hasMany = [personAddress: PersonAddress]
static mapping = {
cache true
personAddress cache: true
}
}
class PersonAddress {
static belongsTo = [person: Person, address: Address]
static mapping = {
cache true
person cache: true
address cache: true
}
}
class Address {
static hasMany = [personAddress: PersonAddress]
static mapping = {
cache true
personAddress cache: true
}
}
Upvotes: 0
Views: 1118
Reputation: 691635
XxxtoOne
associations can't be cached. However, in most of the cases, a XxxToOne association is mapped using a foreign key that is in the table mapped by the entity itself. So, the association is already cached as part of the entity itself.
It could only be useful in the case of a ManyToOne using a join table (very rare), or in case of the inverse side of a OneToOne association (where the foreign key is in the other table). I don't know if Hibernate uses the cache of the associated entity in this case, but it could.
Upvotes: 1