【发布时间】:2014-08-07 03:28:34
【问题描述】:
我在休眠时遇到了这个问题。情况是我正在改造我的项目。我以前的项目是使用 JMS,它可以与我的 POJO 顺利运行。现在我正在尝试使用 Apache Mina(套接字编程)和 Google 的 Gson 重新创建它。
我的字段延迟加载有问题,因为使用 JMS 的项目在延迟加载时运行平稳,但现在我试图在数据库中检索一些值,但总是有一个休眠异常 g 指出 failed to lazily initialize a collection of role: class.field, no session or session was closed我想懒加载,我不想每次都检索它。
public class User {
@Id
@GeneratedValue
@Column(name = "iduser")
private Integer iduser;
@Column(name = "firstname")
private String firstname;
@Column(name = "lastname")
private String lastname;
// this field causes the lazy loading exception
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
@BatchSize(size = 4)
private Set<Transaction> transaction;
}
我正在像这样在我的 DAO 中检索它
public User findByUser(String username, String pass) {
// TODO Auto-generated method stub
try {
User instance = (User) getSession().createCriteria(User.class)
.add(Restrictions.eq(USERNAME, username))
.add(Restrictions.eq(PASS, pass)).uniqueResult();
return instance;
} catch (RuntimeException re) {
throw re;
}
}
我调用服务的方法
public ModelAndView processSignin(User currentUser, BindingResult result,
HttpServletRequest request) {
User user = service.signin(currentUser);
//i try to convert it to GSON but when i comment this line of code it works fine. but when gson tries to convert it to json string it seems that the annotations are being executed
System.out.println(gson.toJson(user));
}
调用DAO类的signin方法
public User signinDealer(User user) {
// TODO Auto-generated method stub
User currentUser = userDAO.signinUser(user);
return currentUser;
}
【问题讨论】: