Announcement Announcement Module
No announcement yet.
using getSession() instead of hibernateTemplate Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • #16
    You are correct, the config is more complex than usual.
    A combination of legacy code and being embedded within another framework.

    The Data objects are [http]Session stateful; so we make one as each user logs in; hence the prototype.
    And because we pass an argument to the prototype, we use a static factory method.
    That is just to explain the stacktrace, i don't believe that is effecting the AoP/TransactionIntercepter.
    [The other 'complexity' you may notice is injecting the txManager to sessionData;
    that is for my next question about controlling commits... but is not used/impacting the current scenario]

    And yes, Data implements (a couple of) Interfaces, and again, that part is working;
    as is apparent when we get the correct Session, transactions are auto-created and auto-closed.

    Is there a reason that the LocalSessionFactoryBean would be confused in face of a prototype object?
    As you see, the TransactionInterceptor appear to be there...

    Given the correct value from 'getSession()' everything works.
    So, how do we get the correct value from getSession without ServerFactoryUtils?

    Without yet looking at the source for LocalSessionFactoryBean, i wonder about this:
    Other parts of the code (the UserDetailsService that is calling newData) still use native Hibernate,
    so there is probably a ThreadLocal or Session-bound native Hibernate Session lurking...
    Could *that* be what is interfering??
    Last edited by Jack Punt; Apr 17th, 2009, 05:37 PM. Reason: clarify text


    • #17
      To reduce the complexity/confusion, i've reduced it to a simple test case.
      This is the entire code; no app server, no other framework.
      Just this class in an interpreter that invokes:
       appctx = ClassPathXmlApplicationContext( "project-test.xml" );
       testbean = appctx.getBean("test");
       testbean.doTest(true);   // sf.getSession()
       testbean.doTest(false);  // sessionFactoryUtils.getSession(sf, false)
      The code:
      package; // Generated package name
      public interface ITest {
      	public Object getTest(boolean flag);
      	public Object doTest(boolean flag);
      import org.hibernate.Session;
      import org.hibernate.SessionFactory;
      import org.springframework.orm.hibernate3.SessionFactoryUtils;
      import org.slf4j.Logger;
      import org.slf4j.LoggerFactory;
      public class TestTrans implements ITest {
      	// Spring setter: (for Hibernate 3.1 DAO pattern)
      	public void setSessionFactory(SessionFactory sf) { this.sessionFactory = sf; }
      	private SessionFactory sessionFactory;
      	public Session getSession1() { return sessionFactory.getCurrentSession(); }
      	public Session getSession2() { return SessionFactoryUtils.getSession(sessionFactory, false);}
      	public Session getSession()  { return getSession2(); }
      	public Object getTest(boolean flag) {
      		Session rv = flag? getSession1() : getSession2();
      		System.out.printf("session=@%x: %s \n",System.identityHashCode(rv),rv);
      		rv.createQuery("from User");
      		return rv;
      	public Object doTest(boolean flag)  {
      		Session rv = flag? getSession1() : getSession2();
      		System.out.printf("session=@%x: %s \n",System.identityHashCode(rv),rv);
      		rv.createQuery("from User");
      		return rv;
      The config (project-trans.xml):
      <?xml version="1.0" encoding="UTF-8"?>
      <beans xsi:schemaLocation="
          <!-- Based on Chapter 9; and DAO (Data/UserData) extends HibernateDaoSupport. -->
          <!-- Hibernate local transactions: -->
          <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
              <property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration"/>
              <property name="configLocations">
          <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
              <property name="sessionFactory" ref="sessionFactory" />
        <!-- the transactional advice (i.e. what 'happens'; see the <aop:advisor/> bean below) -->
        <tx:advice id="txAdvice" transaction-manager="txManager">
          <!-- the transactional semantics... -->
            <!-- all methods starting with 'get' are read-only -->
            <tx:method name="get*" read-only="true"/>
            <tx:method name="find*" read-only="true"/>
            <!-- other methods use the default transaction settings (see below) -->
            <tx:method name="*"/>
        <!-- ensure that the above transactional advice runs for any execution
            of an operation defined by the FooService interface -->
          <aop:pointcut id="itest" expression="execution(public **(..))"/>
          <aop:advisor advice-ref="txAdvice" pointcut-ref="itest"/>
        <bean id="test" class="">
          <property name="sessionFactory" ref="sessionFactory"/>
      The results (my apologies for the scheme syntax... the java-based interpreter pre-dates beanshell)
      Fri Apr 17 16:33:21 PDT 2009
      -> (initAppCtx "project-test.xml")[email protected]: 
      display name [[email protected]];
      startup date [Fri Apr 17 16:33:25 PDT 2009]; root of context hierarchy
      -> (define testbean (appctx.getBean. "test"))
      [email protected]
      -> (testbean.doTest. #!true)
      [email protected]: SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];
      ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]]) 
      org.hibernate.HibernateException: createQuery is not valid without active transaction
      Eval: (testbean.doTest. true)
      Invo: ($Proxy19.doTest [email protected] true)
      TopLevel: createQuery is not valid without active transaction
      -> (testbean.doTest. #!false)
      [email protected]: SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];
      ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]]) 
      -> (testbean.doTest. #!true)
      [email protected]: SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];
      ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]]) 
      org.hibernate.HibernateException: createQuery is not valid without active transaction
      Eval: (huds.doTest. true)
      Invo: ($Proxy19.doTest [email protected] true)
      TopLevel: createQuery is not valid without active transaction
      -> (showStackTrace)
      org.hibernate.HibernateException: createQuery is not valid without active transaction
      	at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(
      	at $Proxy21.createQuery(Unknown Source)
      	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      	at sun.reflect.NativeMethodAccessorImpl.invoke(
      	at sun.reflect.DelegatingMethodAccessorImpl.invoke(
      	at java.lang.reflect.Method.invoke(
      	at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(
      	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(
      	at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(
      	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(
      	at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(
      	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(
      	at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(
      	at $Proxy19.doTest(Unknown Source)
      As you can see; the TransactionInterceptor is working fine with "false": getSession2()
      but it not creating/closing any transaction for "true" : getSession1();
      The proxy is there, but it is working on different Sessions.
      We see that getSession1() continues to return the same Session...


      • #18
        post your 2 cfg.xml files. There must be something wrong with your configuration....


        • #19
          Marten, thank you for looking in to this.
          The database configuration, FWIW:

          <?xml version="1.0" encoding="UTF-8"?>
          <!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                  <property name="hibernate.c3p0.idle_test_period">3600</property>
                  <property name="hibernate.c3p0.max_size">20</property>
                  <property name="hibernate.c3p0.max_statements">50</property>
                  <property name="hibernate.c3p0.min_size">0</property>
                  <property name="hibernate.c3p0.timeout">7200</property>
                  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
                  <property name="hibernate.connection.password">*********</property>
                  <property name="hibernate.connection.url">jdbc:mysql://mysql_host/customerdb</property>
                  <property name="hibernate.connection.username">*********</property>
                  <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
                  <property name="hibernate.format_sql">true</property>
                  <property name="hibernate.show_sql">true</property>
                  <mapping class="" />
                  <!-- more classes/tables in the real thing -->
          <?xml version='1.0' encoding='utf-8'?>
          <!DOCTYPE hibernate-configuration PUBLIC
          		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          		<!-- Enable Hibernate's automatic session context management -->
          		<property name="current_session_context_class">thread</property>
          		<!-- Disable the second-level cache	 -->
          		<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
                  <property name="hibernate.format_sql">false</property>
                  <property name="hibernate.show_sql">false</property>
          Please confirm: we are not using/expecting HibernateTransactionManager.hibernateManagedSessio n=true

          I stepped through the code, and notice that Spring's HibernateTransactionManager (v2.5.5) eventually does this:
              // Bind the session holder to the thread.
              if (txObject.isNewSessionHolder()) {
                 TransactionSynchronizationManager.bindResource(getSessionFactory(), txObject.getSessionHolder());
          Which is where Spring's SessionFactoryUtils.getSession(..) finds the SessionHolder and Session.
          But Hibernate's SessionFactoryImpl.getCurrentSession() is looking for a CurrentSessionContext object
          [which the Spring code does not seem to coordinate with. ]

          By the way, I have: Hibernate-Version: 3.2.4.sp1 (with Spring 2.5.4 and now 2.5.5)
          Is there some other version where Spring and Hibernate actually agree on where and how to do Thread-bound Session?


          • #20
            Tread setting

            In this your concrete case I see only one point in your configuration that may cause the problem. Actually it is <property name="current_session_context_class">thread</property> remove it at all.

            But the strangest thing it did not help me even though I have similar configuration you have already seen so I start wandering if I need to recover the old code there all data managers inherited from HibernateDaoSupport.


            • #21
              I don't know where that property came from...
              But you are right! removing that, the transaction management works!
              (some hibernate example from way back, i suppose; but debunked here)

              I hope that encourages you to find the solution to your problem.

              Thank you (and Marten, whom I'm sure will also spot that problem when the sun again rises in Netherland)
              Last edited by Jack Punt; Apr 18th, 2009, 04:33 PM.


              • #22
                Well the sun rose about 2 hours ago here . Indeed I spotted the culprit (as I already suspected that is why I asked for your configuration files).

                Good luck in further migrating and completing your application.