I'm sorry to ask such a basic question but I could not find a clear answer in others' questions:
I have a class Foo
public class Foo {
private Integer id;
private String name;
private Bar bar;
// getters and setters
}
And another class Bar
public class Bar {
private Integer id;
private String name;
private Set<Foo> foos;
// getters and setters
}
I have a ManagedBean which has a ManagedProperty like this:
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();
}
}
}
}
And in my facelet I try to show the data thisway:
<h:outputText value="#{fooBean.foo.bar.name}" />
Which doesn't work! but If I add bar.getName() to my initialize method (after loading the bar) it works fine!
Why? And what is a best practice alternative?