Pregunta

Intenté esto:

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

}

Cuando llame a getMainSubjects.html? Id = 1 obtengo el error:

net.sf.json.jsonexception: org.hibernate.lazyinitializationException: no pudo inicializar perezosamente una colección de rol: fi.utu.tuha.domain.mainsubjects.aiforms, ninguna sesión o sesión se cerró

¿Como arreglar?

¿Fue útil?

Solución

El problema es que su modelo de objeto MainSubjets tenía algunas asociaciones (construidas por OneTomany, Manytoone, etc.), listas (bolsas persistentes), conjuntos o algo (colección) como esta que se inicializó perezosamente. Significa que, después de la inicialización del conjunto de resultados, Mainsubjects no apunta a un objeto de recolección real, sino proxies. Al renderizar, acceder a estas colecciones, Hibernate intenta obtener los valores de la base de datos utilizando proxies. Pero en este punto no hay sesión abierta. Por esa razón obtienes esta excepción.

Puede establecer su estrategia de recuperación en ansiosos (si usa anotaciones) como esta: @Onetomany (fetch = fetchType.Eager)

En este método, debe ser consciente de que no puede permitir que más de un bolso persistente se inicialice con entusiasmo.

O puede usar el patrón OpenSessionInview, que es un filtro de servlet abre una nueva sesión antes de que su solicitud sea la mano por controlador, y se cierre antes de las respuestas de su aplicación 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();

        }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top