我正在尝试从表中获取所有用户的电子邮件。实体用户:
@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>();
.....
}
在服务中,我正在获取用户并尝试查看电子邮件:
User user = userDAO.getUserById(id);
if (user == null) {
throw new Exception("User not found");
} else {
List<Email> addresses = user.getCommunicationAddresses();
}
但我收到了下一个例外:
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)
获取用户的方法:
@Transactional
@Override
public User getUserById(Long userId) {
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(User.class);
criteria.add(Restrictions.eq("id", userId));
return (User) criteria.uniqueResult();
}
我知道当我使用 Criteria 获取 User 时,我必须获取communicationAddresses... 怎么做?谢谢大家。