[hibernate-issues] [Hibernate-JIRA] Commented: (HHH-1403) SessionException: Session is closed when Serialize and object

S Romender Singh (JIRA) noreply at atlassian.com
Tue Dec 2 10:55:17 EST 2008


    [ http://opensource.atlassian.com/projects/hibernate/browse/HHH-1403?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=31852#action_31852 ] 

S Romender Singh commented on HHH-1403:
---------------------------------------

Hi,

/**
     * Cierra la cession;
     *
     */
    public static void closeSession() {
        try {
            Session s = getSession();
            log.debug("Take session from thread");
            if ((s != null)) {
                log.debug("Closing session");
                s.close();
            }
        } catch (HibernateException ex) {
            log.error("Error closing session session - " + ex.getMessage());
            throw new DCMHibernateException(ex);
        }
    }

While closing the session please nullify the Session present in the ThreadContext .
This will help you.

> SessionException: Session is closed when Serialize and object
> -------------------------------------------------------------
>
>                 Key: HHH-1403
>                 URL: http://opensource.atlassian.com/projects/hibernate/browse/HHH-1403
>             Project: Hibernate Core
>          Issue Type: Bug
>          Components: core
>    Affects Versions: 3.1.1
>         Environment: Mysql 4.x - Hibernate 3.1.1 - Jvm 1.4.2_08
>            Reporter: Juan Pablo Royo
>            Priority: Blocker
>   Original Estimate: 3 days
>  Remaining Estimate: 3 days
>
> I am using the ThreadLocalContext transaction with hibernate. This application was wrote with hibernate 2.1.7 and work well, but decide migrate to hibernate 3.1.1. 
> I Extended the class ThreadLocalContext to overwrite the next methods:
> protected ConnectionReleaseMode getConnectionReleaseMode() {
> 		return ConnectionReleaseMode.ON_CLOSE;
> 	}
> protected boolean isAutoCloseEnabled() {
> 		return false;
> 	}
> 	protected Session buildOrObtainSession() {
>         Session s = (Session) threadSession.get();
>         try {
>         	if((s!=null && !s.isOpen() )) s = null;
>         	if(s!=null){
>         		if(s.isDirty() || !s.isOpen() || !s.isConnected()){
>         			s.close();
>         			s = null;
>         		}
>         	}
>             if (s == null) {
>                 log.debug("Session is null - take new Session");
>                 s = this.factory.openSession();
>                 threadSession.set(s);
>             }
>             bind(s);
>         } catch (HibernateException ex) {
>             log.error("Error take a new Session - " + ex.getMessage());
>             throw new DCMHibernateException(ex);
>         }
>         return s;
> 	}
> This i do because in the API javadoc, in class ThreadLocalContext say let you a handler more time session in scope.
> The application init, do some stuff with database throw hibernate but when arrive time to save the Object com.mjoy.dcmbase.entities.Sesion (Bussines Object)
> that contain an attribute must be serialize, throws the next stackTrace:
> 27-01-2006 13:34:20 DEBUG [SerializationHelper.serialize:141] Starting serialization of object [{opcionesUsuario={D=com.mjoy.dcmbase.entities.DescTono at 1509443, A=com.mjoy.dcmbase.entities.DescTono at 1eaf705, F=com.mjoy.dcmbase.entities.DescTono at 51ddd2, H=com.mjoy.dcmbase.entities.DcmObject at 192ee25, C=com.mjoy.dcmbase.entities.DescTono at 16e2b70, B=com.mjoy.dcmbase.entities.DescTono at 4aad7f, G=com.mjoy.dcmbase.entities.DescTono at 1a5678, E=com.mjoy.dcmbase.entities.DescTono at 1f07360}, paginado=[com.mjoy.dcmbase.entities.DescTono at afcd0c, com.mjoy.dcmbase.entities.DescTono at ed3007, com.mjoy.dcmbase.entities.DescTono at 1b0caf], ranking=com.mjoy.dcmbase.entities.Ranking at 39b99d}]
> org.hibernate.SessionException: Session is closed!
> 	at org.hibernate.impl.AbstractSessionImpl.errorIfClosed(AbstractSessionImpl.java:50)
> 	at org.hibernate.impl.SessionImpl.getPersistenceContext(SessionImpl.java:1794)
> 	at org.hibernate.proxy.BasicLazyInitializer.getReplacement(BasicLazyInitializer.java:100)
> 	at org.hibernate.proxy.BasicLazyInitializer.invoke(BasicLazyInitializer.java:54)
> 	at org.hibernate.proxy.CGLIBLazyInitializer.intercept(CGLIBLazyInitializer.java:156)
> 	at com.mjoy.dcmbase.entities.Medio$$EnhancerByCGLIB$$52ca026d.writeReplace(<generated>)
> 	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
> 	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
> 	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
> 	at java.lang.reflect.Method.invoke(Method.java:324)
> 	at java.io.ObjectStreamClass.invokeWriteReplace(ObjectStreamClass.java:896)
> 	at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1011)
> 	at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1332)
> 	at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1304)
> 	at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1247)
> 	at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1052)
> 	at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:278)
> 	at java.util.HashMap.writeObject(HashMap.java:980)
> 	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
> 	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
> 	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
> 	at java.lang.reflect.Method.invoke(Method.java:324)
> 	at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:809)
> 	at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1296)
> 	at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1247)
> 	at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1052)
> 	at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:278)
> 	at org.hibernate.util.SerializationHelper.serialize(SerializationHelper.java:148)
> 	at org.hibernate.util.SerializationHelper.serialize(SerializationHelper.java:172)
> 	at org.hibernate.type.SerializableType.toBytes(SerializableType.java:74)
> 	at org.hibernate.type.SerializableType.deepCopyNotNull(SerializableType.java:70)
> 	at org.hibernate.type.MutableType.deepCopy(MutableType.java:25)
> 	at org.hibernate.type.TypeFactory.deepCopy(TypeFactory.java:323)
> 	at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:255)
> 	at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:167)
> 	at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:101)
> 	at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:186)
> 	at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:175)
> 	at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:98)
> 	at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
> 	at org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:529)
> 	at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:521)
> 	at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:517)
> 	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
> 	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
> 	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
> 	at java.lang.reflect.Method.invoke(Method.java:324)
> 	at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:292)
> 	at $Proxy0.saveOrUpdate(Unknown Source)
> 	at com.mjoy.dcmbase.persistence.PersistenceManager.saveOrUpdate(PersistenceManager.java:247)
> 	at com.mjoy.dcmbase.entities.Sesion.saveOrUpdate(Sesion.java:221)
> 	at com.mjoy.dcm.handler.RankingLogic.empiezaTransaccion(RankingLogic.java:104)
> 	at com.mjoy.dcm.handler.VentaRankingHandler.execute(VentaRankingHandler.java:76)
> 	at com.mjoy.dcm.servlets.DCM.doAction(DCM.java:115)
> 	at com.mjoy.dcm.servlets.DCM.doGet(DCM.java:149)
> 	at javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
> 	at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
> 	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:237)
> 	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157)
> 	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:214)
> 	at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
> 	at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
> 	at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:198)
> 	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:152)
> 	at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
> 	at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
> 	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137)
> 	at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
> 	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:118)
> 	at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:102)
> 	at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
> 	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
> 	at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
> 	at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
> 	at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:929)
> 	at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:160)
> 	at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:799)
> 	at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:705)
> 	at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:577)
> 	at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:683)
> 	at java.lang.Thread.run(Thread.java:534)
> 27-01-2006 13:34:22 DEBUG [PersistenceManager.saveOrUpdate:250] Error save or updating object - com.mjoy.dcmbase.entities.Sesion 
>  Session is closed!
> 27-01-2006 13:34:22 ERROR [Sesion.saveOrUpdate:223] Error saving sesion
> org.hibernate.SessionException: Session is closed!
> I post in the hibernate Forum but nobody can help me.
> below i write the code with mapping Sesion class and with the code when call the saveOrUpdate(obj) and throw excpetion describe above
> -Mapping class Sesion:
> <?xml version="1.0" encoding="UTF-8"?>
> <!DOCTYPE hibernate-mapping PUBLIC
>     "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
>     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
> <hibernate-mapping
> >
>     <class
>         name="com.mjoy.dcmbase.entities.Sesion"
>         table="sesion"
>     >
>         <id
>             name="id"
>             column="id"
>             type="java.lang.Long"
>             unsaved-value="null"
>         >
>             <generator class="native">
>               <!--  
>                   To add non XDoclet generator parameters, create a file named 
>                   hibernate-generator-params-Sesion.xml 
>                   containing the additional parameters and place it in your merge dir. 
>               --> 
>             </generator>
>         </id>
>         <property
>             name="atributos"
>             type="serializable"
>             update="true"
>             insert="true"
>             column="datos"
>             not-null="false"
>             unique="false"
>         />
>         <property
>             name="linea"
>             type="java.lang.Long"
>             update="true"
>             insert="true"
>             column="linea"
>             not-null="false"
>             unique="false"
>         />
>         <property
>             name="status"
>             type="java.lang.Integer"
>             update="true"
>             insert="true"
>             column="status"
>             not-null="false"
>             unique="false"
>         />
>         <property
>             name="fecha"
>             type="java.sql.Timestamp"
>             update="true"
>             insert="true"
>             column="fecha"
>             not-null="false"
>             unique="false"
>         />
>         <!--
>             To add non XDoclet property mappings, create a file named
>                 hibernate-properties-Sesion.xml
>             containing the additional properties and place it in your merge dir.
>         -->
>     </class>
>         <query name="ObtenerSesionLinea"><![CDATA[
>             from Sesion as s where s.linea like :linea
>         ]]></query>
> </hibernate-mapping>
> -PersistenceManager Class:
>   /**
>      *
>      * Este metodo tiene la siguiente funcionalidad:
>      *
>      *
>      * @return
>      */
>     private static SessionFactory instancia() {
>         if (sessionFactory == null) {
>             try {
>                 Configuration cfg = new Configuration();
>                 log.debug("Iniciando configuración de hibernate");
>                 cfg.configure();
>                 sessionFactory = cfg.buildSessionFactory();
>                 log.debug("Obtienendo SessionFactory ");
>             } catch (HibernateException e) {
>                 log.error("Error initialize Session Factory hibernate :" +
>                     e.getMessage());
>                 throw new DCMHibernateException(e.getMessage());
>             } catch (Exception e) {
>                 e.printStackTrace();
>             }
>         }
>         return sessionFactory;
>     }
>     /**
>      * Cierra la cession;
>      *
>      */
>     public static Session getSession() {
>         try {
>            beginTransaction();
>            return instancia().getCurrentSession();
>         } catch (HibernateException ex) {
>             log.error("Error closing session session - " + ex.getMessage());
>             throw new DCMHibernateException(ex);
>         }
>     }
>     
>     
>     /**
>      * Cierra la cession;
>      *
>      */
>     public static void closeSession() {
>         try {
>             Session s = getSession();
>             log.debug("Take session from thread");
>             if ((s != null)) {
>                 log.debug("Closing session");
>                 s.close();
>             }
>         } catch (HibernateException ex) {
>             log.error("Error closing session session - " + ex.getMessage());
>             throw new DCMHibernateException(ex);
>         }
>     }
>     /**
>      * Inicia una transaccion
>      *
>      */
>     public static void beginTransaction() {
>         try {
>         	Session s = instancia().getCurrentSession();
>         	if(s.getTransaction()!=null && s.getTransaction().isActive()){
>         		log.debug("Ya existe la transaccion y Esta Activa");
>         		return;
>         	}else if(s.getTransaction()!=null){
>         		log.debug("Ya existe transaccion pero no esta activa ........");
>         		s.getTransaction().begin();
>         		log.debug("Activando una nueva..........");
>         	}else{
>         		log.debug("Iniciando una nueva transaccion");
>         		s.beginTransaction();
>         	}
>         } catch (HibernateException ex) {
>             log.error("Error taking new transaction object - " +
>                 ex.getMessage());
>             throw new DCMHibernateException(ex);
>         }
>     }
>     /**
>      * Comitea las transacciones y cierra las sesiones
>      *
>      */
>     public static void commitTransaction() {
>         Transaction tx = (Transaction) getSession().getTransaction();
>         log.debug("Trake transaction from thread");
>         try {
>             if ((tx != null) && !tx.wasCommitted() && !tx.wasRolledBack()) {
>                 log.debug("Commiting transaction before closing");
>                 tx.commit();
>             }
>         } catch (HibernateException ex) {
>             log.error("Error commiting transaction - " + ex.getMessage());
>             rollbackTransaction();
>             throw new DCMHibernateException(ex);
>         } finally {
>             log.debug("Close sesion transaction");
>             closeSession();
>         }
>     }
>    /**
>      * Realiza un rollback si ocurre un error
>      *
>      */
>     public static void rollbackTransaction() {
>         Transaction tx = (Transaction) getSession().getTransaction();
>         log.debug("Take transaction from thread");
>         try {
>             if ((tx != null) && !tx.wasCommitted() && !tx.wasRolledBack()) {
>                 log.debug("Rollbak transaction");
>                 tx.rollback();
>             }
>         } catch (HibernateException ex) {
>             log.error("Error rollback transaction - " + ex.getMessage());
>             throw new DCMHibernateException(ex);
>         } finally {
>             log.debug("Closing session");
>             closeSession();
>         }
>     }
>     
>   /**
>      * Actualiza o inserta un objeto en la base segun corresponda
>      * @param obj
>      */
>     public static void saveOrUpdate(Object obj) {
>         try {
>             log.debug("Save or Updating object - " + obj.getClass().getName());
>             Session s = getSession();
>             s.saveOrUpdate(obj);
>         } catch (HibernateException e) {
>         		e.printStackTrace();
>                 log.debug("Error save or updating object - " +
>                     obj.getClass().getName() + " \n " + e.getMessage());
>                 throw new DCMHibernateException(e);
>         }
>     }
> Please i want to kwon if this is a bug or i had very poor ackwonlegde to version hibernate 3.1.1 handler session.
> I want to migrate to hibernate 3.1 but if this not work i return to 2.1.x version
> Thank you 

-- 
This message is automatically generated by JIRA.
-
If you think it was sent incorrectly contact one of the administrators: http://opensource.atlassian.com/projects/hibernate/secure/Administrators.jspa
-
For more information on JIRA, see: http://www.atlassian.com/software/jira

       




More information about the hibernate-issues mailing list