java - Spring中的Json错误

标签 java json hibernate spring-mvc lazy-initialization

我试过这个:

@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/

相关文章:

java - 给定一个整数数组 [x0 x1 x2],你如何计算从 [0 0 0] 到 [x0 x1 x2] 的所有可能排列?

java - 流有序/无序问题

javascript - 在javascript中为多个JSON对象解析JSON

Python 与 Jython - MuleSoft

java - HiLo 生成器策略不起作用

java - 在 Hibernate 中使用 @SecondaryTable 时出现问题

java - 在测试期间排除 Spring Boot 中的 ApplicationListener @Component

java - 如何用点之前的单词替换字符串中的点 ('.' )?

c# - 从 RESTful API 加载许多 Base64 图像

java - 服务器上存在的交易从不调用