[英]Getting Entities with a OneToMany relationship
I have two entities in the program 我在程序中有两个实体
@Entity
@Table(name = "users")
public class User {
@OneToMany(mappedBy = "senderUser")
private List<Message> sentMessages;
@OneToMany(mappedBy = "recipientUser")
private List<Message> receivedMessages;
and 和
@Entity
@Table(name = "messages")
public class Message {
@ManyToOne
@JoinColumn(name = "sender")
private User senderUser;
@ManyToOne
@JoinColumn(name = "recipient")
private User recipientUser;
As it seems to me, when you download a user during logon, you will be mingled with his message along with these two lists. 在我看来,当您在登录过程中下载用户时,您的信息将与这两个列表混合在一起。 But I wanted to check it out and just display the size of one of these lists on the screen, because I have 2 messages in the database, while displaying in controller
但是我想检查一下,只在屏幕上显示这些列表之一的大小,因为我在数据库中有2条消息,而在控制器中显示
System.out.println("Length: " + ((User) session.getAttribute("user")).getReceivedMessages().size());
Throws a bug in the browser 在浏览器中引发错误
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
and 和
Root Cause
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.jonki.Entity.User.receivedMessages, could not initialize proxy - no Session
It looks like there is a problem with the session, but what? 会话似乎有问题,但是怎么办?
Suppose your User class should be modified like below. 假设您的User类应按如下所示进行修改。
User.java 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;
add following entry to your hibernate.cfg.xml as below. 将以下条目添加到您的hibernate.cfg.xml中,如下所示。
<property name="hibernate.enable_lazy_load_no_trans" value="true"/>
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.