LazyInitializationException when using ElementCollection in Play framework
hibernate, java, jpa, playframework
Solution
By default, `XxxToMany` associations and element collections are lazy loaded.
This means that the collection elements are loaded from the database only when needed, when one of the collection methods is called. But of course, the entity needs to be attached to its session for this to work. If the session is closed, the exception you got is thrown.
Either you make it eagerly loaded by setting the fetch attribute of the annotation, or you use a query or service that initialize the collection, in the transaction, before returning it. Beware that if you make it eagerly loaded, it will ALWAYS be eagerly loaded, even if you don't need the collection elements.
Problem
I have an User entity in my applications set of models that is defined as follows: ``` public class User extends Model { private String name; private byte[] sk; @Column(columnDefinition = "BINARY(272)") private byte[] pk; private int port; @OneToOne public Profile profile; @ElementCollection public List<String> friends; @ElementCollection public List<String> mirrors; ... } ``` and in a method in a different part of my application (a controller class) I am retrieving and attempting to modify the list of mirrors as follows: ``` User u = User.connect(username); int port = ProfileFinder.getLocation(username, mirror); u.mirrors.remove(mirror); u.save(); ``` This is throwing an error stating that: ``` LazyInitializationException occured : failed to lazily initialize a collection of role: models.User.mirrors, no session or session was closed ``` I suspect this is due to me misunderstanding some element of the `@ElementCollection` tag, but can anyone clarify how I could rectify this? Thanks.