Domanda

Ho provato questo:

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

}

?

Quando si chiama getmainsubjects.html id = 1 ottengo l'errore:

net.sf.json.JSONException: org.hibernate.LazyInitializationException: non è riuscito a inizializzare pigramente una raccolta di ruolo: fi.utu.tuha.domain.Mainsubjects.aiForms, nessuna sessione o la sessione è stata chiusa

Come risolvere?

È stato utile?

Soluzione

Il problema è, il vostro oggetto del modello Mainsubjects avuto alcune associazioni (costruiti da OneToMany, ManyToOne, ecc), elenchi (PersistentBags), Imposta o qualcosa (Collection) come questo which're inizializzato pigramente. Significa, dopo l'inizializzazione del set di risultati, Mainsubjects non punta a un oggetto raccolta effettiva, invece proxy. Mentre il rendering, l'accesso a questa collezione, Hibernate cerca di ottenere i valori dal database utilizzando proxy. Ma a questo punto non c'è aperto sessione. Per questo motivo si ottiene questa eccezione.

È possibile impostare la vostra strategia di recupero per EAGER (se si utilizzano le annotazioni) in questo modo: @OneToMany (prendere = FetchType.EAGER)

In questo metodo si deve essere consapevoli, che non si può permettere più di una PersistentBag inizializzato con entusiasmo.

oppure è possibile utilizzare modello OpenSessionInView, che è un filtro servlet si apre una nuova sessione prima della richiesta di handeled dal regolatore, e chiude prima le risposte di applicazioni 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();

        }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top