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

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

问题描述

  public class User extends Model {我有一个用户实体在我的应用程序模型集中,定义如下: 

私人字符串名称;

private byte [] sk;

@Column(columnDefinition =BINARY(272))
private byte [] pk;

private int port;

@OneToOne
公开的个人资料档案;

@ElementCollection
public List< String>朋友;

@ElementCollection
public List< String>镜子;
...
}

以及在不同部分的方法我的应用程序(一个控制器类)我正在检索并尝试修改镜像列表,如下所示:

 用户u =用户。连接(用户名); 
int port = ProfileFinder.getLocation(username,mirror);
u.mirrors.remove(mirror);
u.save();

这是一个错误,指出:

  LazyInitializationException发生:无法懒惰地初始化角色集合:models.User.mirrors,没有会话或会话已关闭

我怀疑这是由于我误解了 @ElementCollection 标记中的某个元素,但任何人都可以澄清我怎么能纠正此问题?



谢谢。

解决方案

延迟加载c $ c> XxxToMany 关联和元素集合。

这意味着集合元素只在需要时才从数据库加载,当调用其中一种收集方法时。但是,当然,这个实体需要被附加到它的会话中才能工作。如果会话已关闭,则抛出异常。



您可以通过设置注释的fetch属性来加载它,或者使用查询或服务在返回之前在事务中初始化集合。请注意,如果您将其加载,即使您不需要收集元素,它也会始终被加载。


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.

解决方案

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.

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

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