0

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

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?

1 Answers1

0

Suppose your User class should be modified like below.

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.

 <property name="hibernate.enable_lazy_load_no_trans" value="true"/>

Hope this helps.

Rajith Pemabandu
  • 613
  • 7
  • 14
  • Now I have 'failed to lazily initialize a collection of role: com.jonki.Entity.User.receivedMessages, could not initialize proxy - no Session'. It works 'FetchType.EAGER', but I have 'FetchType.LAZY'. – QwertyZxcvbnAsdfg Apr 24 '17 at 00:19
  • share me the hibernate configurations file and it may be helpful. – Rajith Pemabandu Apr 24 '17 at 00:27
  • OK. https://pastebin.com/NjU257Qn and getUser https://pastebin.com/3qAdyi4H – QwertyZxcvbnAsdfg Apr 24 '17 at 00:30
  • suppose you need to add `` in hibernate configurations. please refer this [post](http://stackoverflow.com/questions/21574236/org-hibernate-lazyinitializationexception-could-not-initialize-proxy-no-sess) for more details. – Rajith Pemabandu Apr 24 '17 at 00:38