【问题标题】:Hibernate inheritance and 2nd level cache proxiesHibernate 继承和二级缓存代理
【发布时间】:2015-12-26 01:35:15
【问题描述】:

简单的应用程序在以下实体结构中出现问题

@Entity(name="some_table")
@Inheritance(strategy= InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn( name="TYPE", discriminatorType=DiscriminatorType.STRING )
abstract class EntityBase {
    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    @Column
    private int id;
}

@Entity
@DiscriminatorValue("EntityA")
@Cacheable
class EntityA extends EntityBase {
    @Column
    private int aColumn;
...
}

@Entity
@DiscriminatorValue("EntityB")
@Cacheable
class EntityB extends EntityBase {
    @Column
    private int bColumn;
...
}

@Entity(name="holder_table")
@Cacheable
class HolderEntity {
    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    @Column
    private int id;

    @ManyToOne(fetch=FetchType.LAZY)
    EntityBase holdedEntity;

    ...
}

对于第一次加载或没有缓存,一切正常

从缓存加载 HolderEntity 实例后,holdedEntity 字段由 EntityBase 类型的对象(抽象类)初始化。

伪代码:

def a = HolderEntity.get(1)
assert a.holdedEntity.class!=EntityBase //ok
a = HolderEntity.get(1) // load from cache
assert a.holdedEntity.class!=EntityBase //fails (actually EntityBase_$$_jvstbbe_0)

在使用特殊逻辑从缓存休眠构造实体加载期间: 对于字段,它通过变量类型(它是 EntityBase 类)而不是鉴别器(final Type[] types = subclassPersister.getPropertyTypes(); in DefaultLoadEventListener)检测类类型并调用方法
SessionImpl.internalLoad(String entityName, Serializable id, boolean eager, boolean nullable) 通过休眠缓存中的数据“实例化”抽象类和初始化字段

对于 HoldedEntity 的惰性加载和急切加载,它的工作原理相同 存储在 AbstractEntityPersister.EntityMetamodel 中的类类型。看起来,缓存的字段类型是静态的,但它应该取决于字段的实例

如何在不禁用休眠二级缓存的情况下解决?

Hibernate 4.3.8(4.3.6 和 4.3.11 也经过测试)

更新: test class

【问题讨论】:

    标签: java hibernate caching orm hibernate-mapping


    【解决方案1】:

    这是因为 Hibernate 使用代理进行惰性关联。如果你想禁用代理,你需要在你的实体类映射中添加@Proxy注解:

    @Proxy(lazy=false)
    

    如果您运行this GitHub test,您会看到@Proxy(lazy=false) 解决了您的问题。

    【讨论】:

    猜你喜欢
    • 2014-03-15
    • 2013-08-20
    • 2014-11-28
    • 2011-12-18
    • 2012-12-12
    • 2015-05-14
    • 2016-03-24
    • 2011-05-09
    • 2017-08-10
    相关资源
    最近更新 更多