Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LazyInitializationException when using ElementCollection in Play framework

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.

like image 537
chuuk Avatar asked May 24 '12 17:05

chuuk


People also ask

How do I fix lazy initialization exception?

The right way to fix a LazyInitializationException is to fetch all required associations within your service layer. The best option for that is to load the entity with all required associations in one query.


1 Answers

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.

like image 74
JB Nizet Avatar answered Oct 04 '22 04:10

JB Nizet