在 Play 框架中使用 ElementCollection 时出现 LazyInitializationException [英] LazyInitializationException when using ElementCollection in Play framework

查看:23
本文介绍了在 Play 框架中使用 ElementCollection 时出现 LazyInitializationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序模型集中有一个 User 实体,其定义如下:

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

我怀疑这是由于我误解了 @ElementCollection 标签的某些元素,但谁能澄清我如何纠正这个问题?

I suspect this is due to me misunderstanding some element of the @ElementCollection tag, but can anyone clarify how I could rectify this?

谢谢.

推荐答案

默认情况下,XxxToMany 关联和元素集合是延迟加载的.

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.

要么通过设置注释的 fetch 属性使其急切加载,要么在返回之前在事务中使用初始化集合的查询或服务.请注意,如果你让它急切加载,它总是会急切加载,即使你不需要集合元素.

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.

这篇关于在 Play 框架中使用 ElementCollection 时出现 LazyInitializationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆