我尝试了这个:
@RequestMapping(method = RequestMethod.GET, value = "/getmainsubjects")
@ResponseBody
public JSONArray getMainSubjects( @RequestParam("id") int id) {
List <Mainsubjects> mains = database.getMainSubjects(id, Localization.getLanguage());
JSONArray json = JSONArray.fromObject(mains);
return json;
}
调用getmainsubjects.html?id = 1时出现错误:
net.sf.json.JSONException:org.hibernate.LazyInitializationException:无法延迟初始化角色集合:fi.utu.tuha.domain.Mainsubjects.aiForms,没有会话或会话被关闭
怎么修?
最佳答案
问题是,
您的模型对象Mainsubjects具有一些关联(由OneToMany,ManyToOne等构建),列表(PersistentBags),集合或类似的东西(集合),它们被延迟初始化。这意味着在结果集初始化之后,Mainsubjects并不指向实际的集合对象,而是指向代理。渲染时,访问此集合时,休眠尝试使用代理从数据库获取值。但目前尚无会议开放。因此,您将获得此异常。
您可以将获取策略设置为EAGER(如果使用批注),如下所示:
@OneToMany(fetch = FetchType.EAGER)
在这种方法中,您必须知道,不能允许多个初始化的PersistentBag急切地初始化。
或者您可以使用OpenSessionInView模式,它是一个servlet过滤器,它在控制器处理您的请求之前打开一个新会话,并在您的Web应用程序响应之前关闭:
public class DBSessionFilter implements Filter {
private static final Logger log = Logger.getLogger(DBSessionFilter.class);
private SessionFactory sf;
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
try {
log.debug("Starting a database transaction");
sf.getCurrentSession().beginTransaction();
// Call the next filter (continue request processing)
chain.doFilter(request, response);
// Commit and cleanup
log.debug("Committing the database transaction");
sf.getCurrentSession().getTransaction().commit();
} catch (StaleObjectStateException staleEx) {
log.error("This interceptor does not implement optimistic concurrency control!");
log.error("Your application will not work until you add compensation actions!");
// Rollback, close everything, possibly compensate for any permanent changes
// during the conversation, and finally restart business conversation. Maybe
// give the user of the application a chance to merge some of his work with
// fresh data... what you do here depends on your applications design.
throw staleEx;
} catch (Throwable ex) {
// Rollback only
ex.printStackTrace();
try {
if (sf.getCurrentSession().getTransaction().isActive()) {
log.debug("Trying to rollback database transaction after exception");
sf.getCurrentSession().getTransaction().rollback();
}
} catch (Throwable rbEx) {
log.error("Could not rollback transaction after exception!", rbEx);
}
// Let others handle it... maybe another interceptor for exceptions?
throw new ServletException(ex);
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
log.debug("Initializing filter...");
log.debug("Obtaining SessionFactory from static HibernateUtil singleton");
sf = HibernateUtils.getSessionFactory();
}