我试过这个:
@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: failed to lazily initialize a collection of role: fi.utu.tuha.domain.Mainsubjects.aiForms, no session or session was closed
如何修复?
最佳答案
问题是, 您的模型对象 Mainsubjects 有一些关联(由 OneToMany、ManyToOne 等构建)、列表(PersistentBags)、集合或像这样的东西(集合),它们是延迟初始化的。这意味着,在结果集初始化之后,Mainsubjects 并不指向实际的集合对象,而是代理。在呈现、访问此集合时,hibernate 尝试使用代理从数据库中获取值。但此时没有 session 打开。出于这个原因,你得到这个异常(exception)。
您可以将抓取策略设置为 EAGER(如果您使用注释),如下所示: @OneToMany(fetch=FetchType.EAGER)
在这个方法中你必须知道,你不能允许多个 PersistentBag 急切地初始化。
或者您可以使用 OpenSessionInView 模式,这是一个 servlet 过滤器,在 Controller 处理您的请求之前打开一个新 session ,并在您的 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();
}
关于java - Spring中的Json错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6826421/