Announcement Announcement Module
Collapse
No announcement yet.
Persist() delaying no transaction in progress Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Persist() delaying no transaction in progress

    I've got this persistence problem, I can't manage to persist my Entities to my MySQL database.
    I'm working with Spring+Hibernate and the JpaTransactionManager with an EntityManagerFactory.

    When I call the EntityManager.persist("entity"); I get this log result :

    10:57:32,828DEBUG SharedEntityManagerCreator$SharedEntityManagerInvo cationHandler:184 - Creating new EntityManager for shared EntityManager invocation
    10:57:32,828DEBUG SessionImpl:220 - opened session at timestamp: 12454018528
    10:57:32,937DEBUG AbstractSaveEventListener:307 - delaying identity-insert due to no transaction in progress



    I've found other people with similar problems but never managed to fix mine. I suppose it's due to my transactions.

    here are my configuration files :

    hibernate.properties
    Code:
    hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
    hibernate.c3p0.min_size=1
    hibernate.c3p0.max_size=10
    hibernate.c3p0.timeout=0
    hibernate.c3p0.max_statements=5
    hibernate.c3p0.idle_test_period=3000
    hibernate.show_sql=true
    hibernate.format_sql=true
    hibernate.generate_statistics=true
    hibernate.hbm2ddl.auto=create-drop
    hibernate.hbm2ddl.export=true
    hibernate.hbm2ddl.delimiter=type=InnoDB
    hibernate.transaction.factory_class=org.hibernate.transaction.JDBCTransactionFactory
    hibernate.current_session_context_class=thread
    application-context-ressources.xml

    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <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:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xsi:schemaLocation="
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
     
         <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
    
        <bean id="dataSource"
            class="org.springframework.jdbc.datasource.DriverManagerDataSource"
            p:driverClassName="com.mysql.jdbc.Driver"
            p:url="jdbc:mysql://localhost/ecommerce"
            p:username="xxx"
            p:password="xxx"/>
        <bean id="persistenceUnitManager" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
            <property name="defaultDataSource" ref="dataSource"/>
        </bean>
        
        <bean id="entityManagerFactory"
            class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
            p:dataSource-ref="dataSource">
                <property name="persistenceUnitManager" ref="persistenceUnitManager"/>
                <property name="jpaVendorAdapter">
                                <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
                                    p:database="MYSQL"
                                    p:showSql="true"
                                    p:generateDdl="true"
                                    />
                </property>
        </bean>    
    </beans>

    application-context.xml


    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    
    <beans xmlns="http://www.springframework.org/schema/beans"
            xmlns:p="http://www.springframework.org/schema/p"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:context="http://www.springframework.org/schema/context"
               xmlns:tx="http://www.springframework.org/schema/tx"
               xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
               http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
               http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
        
        
        <context:annotation-config/>
        <context:component-scan base-package="com.mvnCommerce.base" />
        <tx:annotation-driven transaction-manager="transactionManager"/>
        <bean id="transactionManager"
              class="org.springframework.orm.jpa.JpaTransactionManager"
              p:entityManagerFactory-ref="entityManagerFactory"/>
    </beans>
    Here are the code files :

    the Entity inherits an ID from entity base
    User.java

    Code:
    package com.mvnCommerce.web.model;
    
    import com.mvnCommerce.base.model.EntityBase;
    import java.util.Set;
    import javax.persistence.CascadeType;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.JoinColumn;
    import javax.persistence.OneToMany;
    import javax.persistence.Table;
    
    
    @Entity
    @Table(name = "USERS")
    public class User extends EntityBase{
    
      
        @Column(name = "NAME")
        private String name;
        @Column(name = "PASSWORD")
        private String password;
        @Column(name = "AGE")
        private int age;
        @OneToMany(cascade = CascadeType.ALL)
        @JoinColumn(name = "ADRESS")
        private Set<Adress> adresses;
        @OneToMany(cascade = CascadeType.ALL)
        @JoinColumn(name = "BILLING_DETAILS")
        private Set<BillingDetails> billingDetails;
    
        public User() {
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public String getName() {
            return this.name;
        }
    
        public String getPassword() {
            return this.password;
        }
    
        public int getAge() {
            return this.age;
        }
    }
    the service that calls the DAO
    userServiceImpl.java

    Code:
    package com.mvnCommerce.web.service.impl;
    
    import com.mvnCommerce.web.service.*;
    import com.mvnCommerce.web.dao.UserDao;
    import com.mvnCommerce.web.dto.UserDto;
    import com.mvnCommerce.web.dto.Utils.UserDtoUtils;
    import com.mvnCommerce.web.model.User;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Propagation;
    import org.springframework.transaction.annotation.Transactional;
    
    
    @Service
    @Transactional(propagation = Propagation.REQUIRED)
    public class UserServiceImpl implements UserService {
    
        private UserDao userDao;
        private UserDtoUtils userDtoUtils;
        
        @Autowired
        public void setUserDtoUtils(UserDtoUtils userDtoUtils) {
            this.userDtoUtils = userDtoUtils;
        }
    
        @Autowired
        public void setUserDao(UserDao userDao) {
            this.userDao = userDao;
        }
    
        @Override
        public UserDto createUser(UserDto user) throws Exception {
            User u = userDtoUtils.dtoToEntity(new User(),user);
                userDao.addUser(u);
            //Add code to send an email to the new user
    
            return userDtoUtils.ENTITY_TO_DTO.transform(u);
        }
    }
    the Dao
    UserDaoImpl.java

    Code:
    package com.mvnCommerce.web.dao.jpa;
    
    import com.mvnCommerce.web.dao.*;
    import com.mvnCommerce.web.model.User;
    import com.mvnCommerce.base.dao.jpa.DaoBaseImpl;
    
    import org.springframework.stereotype.Repository;
    import org.springframework.transaction.annotation.Propagation;
    import org.springframework.transaction.annotation.Transactional;
    
    /**
     *
     * @author Usuario
     */
        @Repository
    public class UserDaoImpl extends DaoBaseImpl<User> implements UserDao {
    
        public UserDaoImpl() {
            super();
        }
        
        @Override
        @Transactional(propagation = Propagation.REQUIRED)
        public void addUser(User user){
            getEntityManager().persist(user);
        }
    
        @Override
        public boolean userExists(User user){
            try{
                getById(user.getId());
            }catch(Exception e){
                return false;
            }
            return true;
        }
    
    }


    userService.createUser(user); this method is call in my controller.
    This is an amount of code I hope sombody can help me, this is my first hibernate project and I'm only making tests, but I don't manage the easiest

    Thanks a lot in advance.

  • #2
    I've kind of got the same problem than this person http://forum.springsource.org/showpo...93&postcount=8 and when I programaticly add the transaction commands it works. I suppose my problem is due to configuration of annotations. But why ???

    Comment


    • #3
      try adding <tx:annotation-driven/> in the context file.

      Also, you may not require the entries
      [CODE
      <bean class="org.springframework.orm.jpa.support.Persist enceAnnotationBeanPostProcessor" />
      ][/CODE]
      and
      Code:
      <context:annotation-config/>
      .
      at the same time, remove the post processor bean definition.

      Comment


      • #4
        First of all, thanks a lot for replying.
        I've tried your instruction :
        taking off the useless "<bean class="org.springframework.orm.jpa.support.Persist enceAnnotationBeanPostProcessor" />"

        and adding: "<tx:annotation-driven/>"
        by the way I allready had a "<tx:annotation-driven transaction-manager="transactionManager"/>
        "

        but I still have this return : DEBUG AbstractSaveEventListener:307 - delaying identity-insert due to no transaction in progress

        and the database is not updated.
        I first thought it was due to my "myIsam" database but I've switched all my system to innodb and it still doesn't work.

        My temporary solution is putting my transactional code between :
        Code:
        TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
        //code
        transactionManager.commit(status);
        Like this it works perfectly, but however I'd like to use the aspect oriented annotations.

        Thank you very much for your help.

        Comment


        • #5
          hmm. interesting.
          I think the issue is some thing related to the way in which you get the transactionManager.
          try injecting the transactionManager in the dao class.

          use :
          Code:
           @PersistenceContext(unitName = "myPU")
              private EntityManager entityManager;
          then persists the entity by
          Code:
           //entityManager.setFlushMode(FlushModeType.AUTO);
            entityManager.persist(yourDTO);
            // flush
            entityManager.flush();

          if this doesnt work, try uncommeting
          Code:
          entityManager.setFlushMode(FlushModeType.AUTO);
          also let me know how your BaseDaoImpl is implemented(extends/implements what ?)

          Comment


          • #6
            Infact I do the injection of the EntityManager in my DtoBaseImpl, here's the code of it :
            Code:
            package com.mvnCommerce.base.dao.jpa;
            import com.mvnCommerce.base.model.EntityBase;
            import com.mvnCommerce.base.dao.DaoBase;
            import java.lang.reflect.ParameterizedType;
            import org.apache.log4j.Logger;
            import javax.persistence.EntityManager;
            import javax.persistence.PersistenceContext;
            import org.springframework.stereotype.Repository;
            import org.springframework.transaction.annotation.Propagation;
            import org.springframework.transaction.annotation.Transactional;
            
            /**
             *
             * @author Usuario
             */
            @Repository
            public abstract class DaoBaseImpl<T extends EntityBase> implements DaoBase<T>{
            
                @PersistenceContext(unitName="myPU")
                private EntityManager entityManager;
            
                private Class<T> persistentClass;
            
                protected static Logger logger;
            
                protected void setPersistentClass(Class<T> persistentClass) {
                    this.persistentClass = persistentClass;
                }
            
                protected Class<T> getPersistentClass() {
                    return persistentClass;
                }
            
                protected EntityManager getEntityManager() {
                    return entityManager;
                }
            
                public DaoBaseImpl() {
                    Class clazz = getClass();
                    while (!(clazz.getGenericSuperclass() instanceof ParameterizedType)) {
                        clazz = clazz.getSuperclass();
                    }
                    persistentClass = (Class<T>) ((ParameterizedType) clazz.getGenericSuperclass()).getActualTypeArguments()[0];
                    logger = Logger.getLogger(persistentClass);
                    if (logger.isDebugEnabled()) {
                        logger.debug("Created Dao " + persistentClass.toString());
                    }
                }
            
                @Override
                @Transactional(propagation = Propagation.REQUIRED)
                public T getById(Long id) {
                    return this.getEntityManager().find(this.getPersistentClass(), id);
                }
            }
            When I added (unitName="myPU") to my @PersistanceContext I thought I am maybe mixing up @PersistanceContext and @PersistanceUnit!?!
            What do you think about it? Because I have a persistence.xml file containing this :

            Code:
            <?xml version="1.0" encoding="UTF-8"?>
            <persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence ../../lib/persistence_1_0.xsd ">
              <persistence-unit name="mvnCommerce" transaction-type="RESOURCE_LOCAL">
               </persistence-unit>
            </persistence>
            Is ressource local wrong ?


            However, this is my result when using just the flush
            Code:
            13:01:07,312DEBUG SessionImpl:220 - opened session at timestamp: 12460140672
            13:01:07,328DEBUG AbstractSaveEventListener:307 - delaying identity-insert due to no transaction in progress
            13:01:07,328DEBUG SessionImpl:220 - opened session at timestamp: 12460140673
            13:01:07,328ERROR InscriptionController:58 - creation of user failed
            javax.persistence.TransactionRequiredException: no transaction is in progress
                    at org.hibernate.ejb.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:294)
                    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:597)
                    at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:346)
                    at $Proxy67.flush(Unknown Source)
                    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:597)
                    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:193)
                    at $Proxy61.flush(Unknown Source)
                    at com.mvnCommerce.web.dao.jpa.UserDaoImpl.addUser(UserDaoImpl.java:35)
                    at com.mvnCommerce.web.service.impl.UserServiceImpl.createUser(UserServiceImpl.java:42)
                    at com.mvnCommerce.web.controller.InscriptionController.handlePost(InscriptionController.java:56)
                    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:597)
                    at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:160)
                    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:245)
                    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:874)
                    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:808)
                    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:476)
                    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:441)
                    at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
                    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
                    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
                    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
                    at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:390)
                    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
                    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
                    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
                    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
                    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
                    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
                    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
                    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
                    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845)
                    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
                    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
                    at java.lang.Thread.run(Thread.java:619)
            And this is the result by adding entityManager.setFlushMode(FlushModeType.AUTO);
            Code:
            13:13:14,515DEBUG SessionImpl:220 - opened session at timestamp: 12460147944
            13:13:14,515DEBUG SessionImpl:220 - opened session at timestamp: 12460147945
            13:13:14,531DEBUG AbstractSaveEventListener:307 - delaying identity-insert due to no transaction in progress
            13:13:14,531DEBUG SessionImpl:220 - opened session at timestamp: 12460147945
            13:13:14,531ERROR InscriptionController:58 - creation of user failed
            javax.persistence.TransactionRequiredException: no transaction is in progress
            I hope I'm not mixing everything up with the EntityManager or EntityManagerFactory.
            Thanks for helping

            Comment


            • #7
              first of all the unitName in @PersistenceContext(unitName="myPU") should be the name of your PU ie. mvnCommerce

              use
              @PersistenceContext(unitName="mvnCommerce")

              just wanted to clarify that there is no mix-up here with @PersistanceContext and @PersistanceUnit

              try moving this to your implemenation class(should not cause any issue if it is in bae class)

              also in service layer, try moving the transactional annotation to method level.

              if nothing works, try this as well, in definition of entityManagerFactory, add a property "databasePlatform" and remove "database"

              Code:
               <bean id="entityManagerFactory"
                      class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
                      p:dataSource-ref="dataSource">
                          <property name="persistenceUnitManager" ref="persistenceUnitManager"/>
                          <property name="jpaVendorAdapter">
                                          <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"                                p:databasePlatform="org.hibernate.dialect.MySQLDialect"
                                              p:showSql="true"
                                              p:generateDdl="true"
                                              />
                          </property>
                  </bean>

              Comment


              • #8
                Ok Jerishj,
                I've naturally changed the @PersistenceContext(unitName=myPU) to @PersistenceContext(unitName="mvnCommerce"), sorry for being so slow minded.
                I've also tried the other changes, inject the EntityManager in the userDaoImpl, moving the transactional annotations to method level and even changing the database property of the HibernateJpaVendorAdapter to databasePlatform.
                But unfortunately the log output remains to :
                Code:
                13:13:14,515DEBUG SessionImpl:220 - opened session at timestamp: 12460147944
                13:13:14,515DEBUG SessionImpl:220 - opened session at timestamp: 12460147945
                13:13:14,531DEBUG AbstractSaveEventListener:307 - delaying identity-insert due to no transaction in progress
                13:13:14,531DEBUG SessionImpl:220 - opened session at timestamp: 12460147945
                13:13:14,531ERROR InscriptionController:58 - creation of user failed
                javax.persistence.TransactionRequiredException: no transaction is in progress

                Comment

                Working...
                X