I'm trying to get all user's emails from table. Entity user:
@Entity
@Table(name = "tbl_User")
public class User {
@Expose
@Id
@GeneratedValue
@Column(name = "id")
private Long id;
.....
@OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
List<CommunicationAddress> communicationAddresses = new ArrayList<CommunicationAddress>();
.....
}
In the service I'm getting user and trying to look emails:
User user = userDAO.getUserById(id);
if (user == null) {
throw new Exception("User not found");
} else {
List<Email> addresses = user.getCommunicationAddresses();
}
But I received the next exception:
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:186)
at org.hibernate.collection.internal.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:137)
at org.hibernate.collection.internal.PersistentBag.isEmpty(PersistentBag.java:249)
The method for getting user:
@Transactional
@Override
public User getUserById(Long userId) {
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(User.class);
criteria.add(Restrictions.eq("id", userId));
return (User) criteria.uniqueResult();
}
I understand that I must to get communicationAddresses when I get User using Criteria... How to do it? Thank's all.