Question

J'ai essayé ceci:

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

}

Lors de l'appel getmainsubjects.html id = 1 je reçois l'erreur:

net.sf.json.JSONException: org.hibernate.LazyInitializationException: n'a pas réussi à paresseusement initialiser une collection de rôle: fi.utu.tuha.domain.Mainsubjects.aiForms, aucune session ou session fermée

Comment réparer?

Était-ce utile?

La solution

Le problème est, votre modèle objet Mainsubjects avait certaines associations (construites par OneToMany, ManyToOne, etc.), listes (PersistentBags), ensembles ou quelque chose (Collection) comme celui-ci which're initialisé paresseusement. Cela signifie, après l'initialisation du jeu de résultats, Mainsubjects ne pointe pas vers un objet de collection réelle, au lieu des procurations. Tout en rendant, l'accès à ces collections, mise en veille prolongée tente d'obtenir les valeurs de base de données en utilisant les procurations. Mais à ce stade, il n'y a pas ouvert de session. Pour cette raison, vous obtenez cette exception.

Vous pouvez définir votre stratégie de récupération à EAGER (si vous utilisez des annotations) comme ceci: @OneToMany (fetch = FetchType.EAGER)

Dans cette méthode, vous devez être conscient que vous ne pouvez pas permettre à plus d'un PersistentBag initialisé avec impatience.

ou vous pouvez utiliser modèle OpenSessionInView, qui est un filtre de servlet ouvre une nouvelle session avant de votre demande handeled par le contrôleur et ferme avant vos réponses d'applications 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();

        }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top