I am using Spring 3.0.5, Hibernate 3.6.7 and Vaadin.
I have a simple entity that is like this
@Entity
public class Foo {
@OneToMany(fetch = FetchType.LAZY)
private Collection<Bar> bars;
...
}
I have a Dialog Window that I get from the context and its supposed to show the ‘bars’ from ‘foo’.
@Component
@Scope("prototype")
public class FooBarDialogImp extends Window implements FooBarDialog {
@Transactional(readOnly = true)
public void populate(Foo foo) {
...
for (Bar bar : foo.getBars()) {
// populate the dialog with bar information
...
}
}
}
And when user ask to show a foo bars, I do something like this
public class FooController {
...
public void showFooBars(Foo foo) {
FooBarDialog dialog = context.getBean(FooBarDialog.class);
dialog.populate(foo);
showDialog(dialog);
}
}
but the problem is that I get a “no session” exception from hibernate. I changed the code to inject the session factory and see if there was a bound session, and it was. I don’t know what I am doing wrong. Anyone have a idea?
You specified your association type for the collection as LAZY, so it does not get loaded until the getter method on the owning object is invoked. The caveat to doing this is that it needs to be in the scope of a session, either the original one that created it or a new one. And the caveat to using a new session to load the lazy list is that your entity is considered detached from it, and first needs to be merged before you can call to get the lazy collection.
So just call:
Before attempting to iterate its
bars.