LazyInitializationException when using ElementCollection in Play framework

前端 未结 4 913
粉色の甜心
粉色の甜心 2021-01-18 16:03

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 b         


        
相关标签:
4条回答
  • 2021-01-18 16:27

    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.

    0 讨论(0)
  • 2021-01-18 16:32

    User transaction on class level

    @Component

    @Transactional

    public class className

    0 讨论(0)
  • 2021-01-18 16:43

    Yes, you should use EAGER annotation, but be careful because, as JB Nizet says, those elements will be always eagerly loaded.

    0 讨论(0)
  • 2021-01-18 16:48

    If you don't want to change from lazy load to eager, you have another option: merge.

    User u = User.connect(username);
    u.merge();
    

    Merge will take an object that is disconnected from the session and reconnect it.

    For example, if you cache an object (in this case an instance of User) you cannot retrieve the user object's mirrors without first using .merge() on the object.

    0 讨论(0)
提交回复
热议问题