在JPA / Hibernate上阅读PostLoad中的Set

时间:2011-08-07 14:11:16

标签: hibernate jpa

我有一个简单的实体与OneToMany关系:

@Column(name = "TITLE")
private String _title;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "PROJECT_ID")
private Set<Device> _devices;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "PROJECT_ID")
private Set<Firm> _firms;

我想在PostLoad方法中使用我的设置

@PostLoad
private void copyToProperty() {
    title.set(_title);
    if (_devices != null && !_devices.isEmpty())
       //DO Stuff HERE
}

但是,当我尝试访问_devices时,我得到了这个例外:

Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.LazyInitializationException: failed to lazily initialize a collection, no session or session was closed
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1215)
at org.hibernate.ejb.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:635)
at org.hibernate.ejb.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:589)
at com.dooapp.jpa.Main.main(Main.java:57)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

有人知道为什么我在获取LazyInitializationException,只要我在FetchType.EAGER上?

怎样才能使这些东西起作用?

感谢的

1 个答案:

答案 0 :(得分:5)

很遗憾,Hibernate不允许你这样做。在@PostLoad方法中,不允许您触摸实体中的任何关联。这是一个长期存在的主要问题。

对于原始错误,请参阅:https://issues.jboss.org/browse/JBAS-5474。关闭错误后(仍未解决),立即在此处重新打开一个新错误:https://hibernate.onjira.com/browse/HHH-6043

如果这个错误导致你(我猜它确实存在),请投票支持。