我在程序中有两个实体
@Entity
@Table(name = "users")
public class User {
@OneToMany(mappedBy = "senderUser")
private List<Message> sentMessages;
@OneToMany(mappedBy = "recipientUser")
private List<Message> receivedMessages;
和
@Entity
@Table(name = "messages")
public class Message {
@ManyToOne
@JoinColumn(name = "sender")
private User senderUser;
@ManyToOne
@JoinColumn(name = "recipient")
private User recipientUser;
在我看来,当您在登录期间下载用户时,您将与他的消息以及这两个列表混在一起。但我想检查一下,只是在屏幕上显示其中一个列表的大小,因为我在数据库中有2条消息,而在控制器中显示
System.out.println("Length: " + ((User) session.getAttribute("user")).getReceivedMessages().size());
在浏览器中引发错误
Exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.jonki.Entity.User.receivedMessages, could not initialize proxy - no Session
和
Root Cause
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.jonki.Entity.User.receivedMessages, could not initialize proxy - no Session
看起来会话有问题,但是什么?
答案 0 :(得分:0)
假设您的User类应该如下修改。
User.java
@Entity
@Table(name = "users")
public class User {
@OneToMany(mappedBy = "senderUser",cascade=CascadeType.ALL,fetch=FetchType.LAZY)
private List<Message> sentMessages;
@OneToMany(mappedBy = "recipientUser",cascade=CascadeType.ALL,fetch=FetchType.LAZY)
private List<Message> receivedMessages;
将以下条目添加到hibernate.cfg.xml中,如下所示。
<property name="hibernate.enable_lazy_load_no_trans" value="true"/>
希望这有帮助。