Announcement Announcement Module
Collapse
No announcement yet.
Spring - Hibernate => Transactions Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Spring - Hibernate => Transactions

    Hello,

    I begin with Spring 3.1.1/Hibernate 4.1.0/Struts 2.2.3.
    I have no error in logs, when i select data all is ok but when i save an object, i have always no error but the object is not save in the mysql database. I think transaction is never commit.

    This is my applicationContext :
    Code:
    <?xml version="1.0" encoding="ISO-8859-15"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:p="http://www.springframework.org/schema/p"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
           http://www.springframework.org/schema/context 
           http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
      <!-- Import de la config hibernate/dao depuis le ccr-core -->
      <import resource="classpath:applicationContext-ccr-hibernate.xml"/>
          
      
      <!-- Activation des annotations -->
      <context:component-scan base-package="fr.cndp.ccr.core.dao"/>      
      <context:component-scan base-package="fr.cndp.ccr.core.service"/>    
         
    </beans>
    This is applicationContext-ccr-hibernate.xml (in a module) :
    Code:
    <?xml version="1.0" encoding="ISO-8859-15"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:p="http://www.springframework.org/schema/p"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
           http://www.springframework.org/schema/context 
           http://www.springframework.org/schema/context/spring-context-3.0.xsd">
         
      <bean id="dataSourceCCR"
         class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://javadev.cndp.lan:3306/ccrdb" />
        <!--<property name="url" value="jdbc:mysql://localhost:3306/ccrdb" />-->
        
        <property name="username" value="db" />
        <property name="password" value="toto" />
      </bean>
      
      <bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" >
        <property name="dataSource" ref="dataSourceCCR" />
        <property name="mappingLocations">
          <value>classpath*:fr/cndp/ccr/core/modele/*.hbm.xml</value>
        </property>
        <property name="hibernateProperties">
          <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
            <prop key="hibernate.show_sql">false</prop>
            <prop key="hibernate.id.new_generator_mappings">true</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
            <prop key="hibernate.validator.apply_to_ddl">false</prop>  
            <prop key="hibernate.connection.release_mode">after_transaction</prop>
            <!--<prop key="current_session_context_class">thread</prop>-->
            <prop key="hibernate.validator.autoregister_listeners">false</prop>  
            <prop key="c3p0.acquire_increment">1</prop> 
            <prop key="c3p0.min_size">1</prop>
            <prop key="c3p0.max_size">20</prop>
            <prop key="c3p0.timeout">0</prop>
            <prop key="c3p0.max_statements">0</prop>
            <prop key="c3p0.idle_test_period">3600</prop>
          </props>
        </property>
      </bean>
      
      
      <!-- Hibernate Transaction Manager Definition -->
      <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
        <property name="dataSource" ref="dataSourceCCR" />
      </bean>
      <tx:annotation-driven transaction-manager="transactionManager" mode="aspectj"/>
    
      <aop:config proxy-target-class="true"/>
      
    </beans>
    My GenericDaoImpl.java :
    Code:
    package fr.cndp.ccr.core.dao;
    
    public abstract class GenericDAOImpl<T, K extends Serializable> implements GenericDAO<T, K> {
    
      protected static Logger logger;
    
      @Resource(name = "sessionFactory")
      private SessionFactory sessionFactory;
      private Session session;
    
      
      private Class type;
    
      public GenericDAOImpl(Class<T> leType) {
        type = leType;
        logger = Logger.getLogger(type);
      }
    
        /**
       * Permet d'enregistrer en base un nouveau T
       * @param instance
       * @return 
       */
      @Override
      public K save(T instance) {
        K reponse = (K) getSession().save(instance);
        return reponse;
      }
    
      public Session getSession() {  
        if (session == null) {
          try {
            session = sessionFactory.getCurrentSession();
          } catch (HibernateException e) {
             session = sessionFactory.openSession();
          }    
                    
        }
       return this.session;
      }
    
      public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
      }
    }
    My implementationof Dao RessourceImplDao.java :
    Code:
    @Repository
    public class RessourceImplDao extends GenericDAOImpl<RessourceImpl, Integer> {
      public RessourceImplDao() {
        super(RessourceImpl.class);
      }
    
    }
    My service RessourceImpService.java that i made in "Transactional":
    Code:
    @Service
    @Transactional
    public class RessourceImplService {
     @Autowired
      private RessourceImplDao ressourceImplDao;
    
      public void enregistrerRessource(RessourceImpl r) {    
        ressourceImplDao.save(r);
      }
    }
    Thanks for you help!

  • #2
    My guess you have duplicate service instances one proxied one not proxied and struts uses the non-proxied one. Post your struts configuration setup as currently we miss crucial information.

    Another note is you have a dangerous getSession method your implementation can lead to unmanaged sessions and due to that unmaged connections which. Basically NEVER use openSession to create a session ALWAYS use getCurrentSession. Also never catch and swallow an exception as that will break proper tx management.

    Also NEVER store your session as an instance variable, imagine you have 1 dao, 100 users.. .Now which session is stored?

    So in short first fix your dao, next you probably get an exception due to the first thing I mentioned.
    Last edited by Marten Deinum; Jun 5th, 2012, 08:02 AM.

    Comment


    • #3
      Thanks for help Marten,

      I'have fixed my GenericDao with :
      Code:
        public Session getSession() {
         return sessionFactory.getCurrentSession();   
        }
      But now i've this exception at excecution :
      Code:
      org.hibernate.HibernateException: No Session found for current thread
      	org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
      	org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1024)
      	fr.cndp.ccr.core.dao.GenericDAOImpl.getSession(GenericDAOImpl.java:116)
      	fr.cndp.ccr.core.dao.UserImplDao.getUser(UserImplDao.java:30)
      	fr.cndp.ccr.core.service.UserImplService.getUser(UserImplService.java:49)
      	fr.cndp.ccr.catalogue.actions.IdentificationAction.identifier(IdentificationAction.java:44)
      	sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      	sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
      	sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
      	java.lang.reflect.Method.invoke(Method.java:597)
      	com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:452)
      	com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:291)
      	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:254)
      	com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176)
      	com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
      	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
      	com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:263)
      	org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
      	com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
      	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
      	com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:133)
      	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
      	com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207)
      	com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
      	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
      	com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207)
      	com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
      	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
      	com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:190)
      	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
      	org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)
      	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
      	org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94)
      	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
      	org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:243)
      	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
      	com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
      	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
      	com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
      	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
      	org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:270)
      	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
      	com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145)
      	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
      	com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171)
      	com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
      	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
      	com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:176)
      	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
      	org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
      	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
      	com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:190)
      	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
      	com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:187)
      	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
      	org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
      	org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:498)
      	org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
      	org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
      	com.opensymphony.sitemesh.webapp.SiteMeshFilter.obtainContent(SiteMeshFilter.java:129)
      	com.opensymphony.sitemesh.webapp.SiteMeshFilter.doFilter(SiteMeshFilter.java:77)
      	org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:164)
      	org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:141)
      	org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:90)
      	org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:417)
      My web.xml :
      Code:
      <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
        <display-name>catalogue-cheque-ressources</display-name>
        <context-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>/WEB-INF/applicationContext.xml</param-value>
        </context-param>
        <listener>
          <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        <!-- Si on utilise pas spring-mvc -->
        <listener>
          <listener-class>org.springframework.web.context.request.RequestContextListener
          </listener-class>
        </listener>
        <filter>
          <filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
          <filter-class>
                  org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter
          </filter-class>
        </filter>
        <filter>
          <filter-name>UrlRewriteFilter</filter-name>
          <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
        </filter>
        <filter-mapping>
          <filter-name>UrlRewriteFilter</filter-name>
          <url-pattern>/*</url-pattern>
        </filter-mapping>
        <filter>
          <filter-name>sitemesh</filter-name>
          <filter-class>com.opensymphony.sitemesh.webapp.SiteMeshFilter</filter-class>
        </filter>
        <filter-mapping>
          <filter-name>sitemesh</filter-name>
          <url-pattern>/*</url-pattern>
        </filter-mapping>
        <filter>
          <filter-name>struts2</filter-name>
          <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
        </filter>
        <filter-mapping>
          <filter-name>struts2</filter-name>
          <url-pattern>/*</url-pattern>
          <dispatcher>FORWARD</dispatcher>
          <dispatcher>REQUEST</dispatcher>
        </filter-mapping>
        <session-config>
          <session-timeout>
                  30
          </session-timeout>
        </session-config>
        <welcome-file-list>
          <welcome-file>redirect.jsp</welcome-file>
        </welcome-file-list>
      </web-app>
      and struts.xml :
      Code:
      <struts>
      <!--  <constant name="struts.objectFactory" value="spring" />-->
        <constant name="struts.objectFactory" value="org.apache.struts2.spring.StrutsSpringObjectFactory" />
        <constant name="struts.devMode" value="true" />
        <package name="basicstruts2" extends="struts-default,json-default">
      
          <!-- CONNEXION/DECONNEXION -->
          <action name="identificationFormAction" class="fr.cndp.ccr.catalogue.actions.IdentificationAction" method="identifierForm">
            <result name="error">identification.jsp</result>      
            <result name="success">identification.jsp</result>
          </action>
      </struts>

      Comment


      • #4
        Which indicates an error in your (transaction) setup.

        As I mentioned in the previous post is I suspect a duplication of services. So my guess is that there is another context file which isloaded by the StrutsSpringObjectFactory which also contains a context:component-scan. Where/how is your IdentificationAction getting the service?

        Another thing I noticed/find strange is that you use hibernate but have configured an EntityManager filter, whereas I would expect a hibernate filter...

        Comment


        • #5
          For my struts action i make this :
          Code:
          @Controller
          public class IdentificationAction extends ActionSupport implements Preparable {
           
            @Autowired
            private UserImplService userService;
          
           // Action 
            public String identifier() {    
              UserImpl userImpl = userService.getUser(this.identifiant, this.motdepasse);
            }
          }
          I remove this filter :
          Code:
          <filter>
              <filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
              <filter-class>
                      org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter
              </filter-class>
            </filter>
          there is no change
          Last edited by flam182; Jun 5th, 2012, 10:21 AM.

          Comment


          • #6
            Regarding your configuration why do you use aspectj as the type for the transactions.

            Why do you have an empty aop:config block and specify that with classproxies?!

            I suggest remove the aop:config (unless you have a real need for it), remove type from tx:annotation-driven and set proxy-target-class to true on the tx:annotation-driven. Also make sure you have cglib in your classpath.

            At the moment there is no (class) proxy, judging by the stacktrace, and as a result no transactions. If you really need the aspectj stuff I suggest a read of the reference guide as you also need to configure loadtime weaving then.

            Comment


            • #7
              Thanks very much, you save me

              I follow your suggestion and i remove all aspectj.
              In applicationContext-ccr-hibernate.xml :
              Code:
              <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
              and i add cglib with maven :
              Code:
                  <dependency>
                    <groupId>cglib</groupId>
                    <artifactId>cglib</artifactId>
                    <version>2.2.2</version>
                  </dependency>

              Comment

              Working...
              X