很抱歉问了这么一个基本的问题,但我在别人的问题中找不到明确的答案:
我有一个类 Foo
public class Foo {
private Integer id;
private String name;
private Bar bar;
// getters and setters
}
还有一个类Bar
public class Bar {
private Integer id;
private String name;
private Set<Foo> foos;
// getters and setters
}
我有一个 ManagedBean
,它有一个像这样的 ManagedProperty
:
public class FooBean {
@ManagedProperty(value = "{param.barId}"
private Integer barId;
private Bar bar;
private Foo foo;
public FooBean() {
}
@PostConstruct
public void initialize() {
SessionFactory factory = new Configuration().configure().buildSessionFactory();
if barId != null) {
foo = new Foo();
Session session = factory.openSession();
try {
session.beginTransaction();
bar = (Bar) session.load(Bar.class, barId);
foo.setBar(bar);
session.getTransaction().commit();
} catch (Exception ex) {
Transaction tx = session.getTransaction();
if (tx.isActive()) {
tx.rollback();
}
} finally {
session.close();
}
}
}
}
在我的 facelet 中,我尝试以这种方式显示数据:
<h:outputText value="#{fooBean.foo.bar.name}" />
这是行不通的!但如果我将 bar.getName()
添加到我的初始化方法(加载栏后),它就可以正常工作!
为什么?什么是最佳实践替代方案?
最佳答案
添加
lazy="false"
用于 hibernate 映射 xml 中的名称属性。
关于java - hibernate 代理问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4659414/