【问题标题】:Hibernate association caching休眠关联缓存
【发布时间】:2012-03-14 00:04:59
【问题描述】:

问题一

根据 Grails 手册

除了使用 Hibernate 的二级缓存来缓存实例的能力之外,您还可以缓存对象的集合(关联)。例如:

class Person {

  static hasMany = [addresses: Address]

  static mapping = { 
    cache true
    addresses cache: true 
  } 
}

如果我们缓存一个人与其地址之间的关联,那么也缓存反向关系是否有意义,例如

class Address {

  static belongsTo = [person: Person]

  static mapping = { 
    cache true
    person cache: true // is this necessary?
  } 
}

显然,如果(在我们的应用程序代码中)我们从 Address 导航到 Person,缓存反向关系才有意义,但假设关系是双向导航的,是否也需要双向缓存?

问题二

上一个问题是关于在 1:N 关系的上下文中进行缓存的。如果两者之间的关系是 1:1,大概可以/应该指定相同的缓存行为?例如:

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
  } 
}

问题三

如果我们在两个对象之间有 N:N 关系,并且我们在两个方向上导航关系,那么以下是缓存关联的正确方法:

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
  } 
}

【问题讨论】:

    标签: hibernate caching grails grails-orm


    【解决方案1】:

    XxxtoOne 关联无法被缓存。但是,在大多数情况下,XxxToOne 关联是使用实体本身映射的表中的外键映射的。因此,关联已作为实体本身的一部分缓存。

    只有在使用连接表的 ManyToOne 的情况下(非常罕见),或者在 OneToOne 关联的反面(外键在另一个表中)的情况下才有用。我不知道 Hibernate 在这种情况下是否使用了关联实体的缓存,但它可以。

    【讨论】:

    • 谢谢。在上述 1:1 关联的情况下(问题 II),外键将在地址表中。那么这是否意味着仅在Person 上指定address cache: true 才有用?
    • 无法缓存 XxxToOne 关联。缓存它们是没有意义的,因为 Hibernate 不支持缓存 XxxToOne 关联。
    • 抱歉,我没有意识到 XxxToOne 意味着 ManyToOne 或 OneToOne。我现在做的。你赢得了复选标记,恭喜你,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-23
    • 1970-01-01
    • 1970-01-01
    • 2015-04-24
    • 2016-08-13
    • 2012-04-29
    相关资源
    最近更新 更多