Getting TransactionRequiredException - Help Required !!!

Discussions

General J2EE: Getting TransactionRequiredException - Help Required !!!

  1. Hi, I am trying to update data. I use the JpaDaoSupport (Spring) based POJO as the DAO layer. HSQL is the back-end. Declarative Transaction Management is used. I have a search & update functionalities. Out of these, search is working fine. whereas update method is throwing javax.persistence.TransactionRequiredException: Executing an update/delete query Source Code: public class SimpleEmployeeViewBuilder extends JpaDaoSupport implements EmployeeViewBuilder { ..... // Search Methods & Other declarations ..... @Transactional(propagation = Propagation.REQUIRED) public void updateEmployeeView(final SimpleEmployeeView view) { EntityManager anEntityManager = getJpaTemplate().getEntityManagerFactory().createEntityManager(); final Query query = anEntityManager.createQuery( "UPDATE employee.pd.Employee emp SET emp.employeeName=? WHERE emp.employeeId =?"); query.setParameter(1, view.getEmployeeName()); query.setParameter(2, view.getEmployeeId()); query.executeUpdate(); //****This is the line throwing exception } } Configuration File : <!--=========== Datasources ===========--> <!--=========== EntityManagerFactory ===========--> .... <!-- AOP Based TRANSACTION MANAGEMENT --> <tx:annotation-driven transaction-manager="txManager" [B]proxy-target-class="true"[/B]/> And, this is the exception stack trace: [CODE] - Adding transactional method [updateEmployeeView] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT] - Using transaction object [org.springframework.orm.jpa.JpaTransactionManager$JpaTransactionObject@1fa5e5e] - Creating new transaction with name [employee.service.EmployeeViewBuilderService.updateEmployeeView]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT - Opened new EntityManager [org.hibernate.ejb.EntityManagerImpl@497062] for JPA transaction - opened session at timestamp: 12138839316 - begin - opening JDBC connection - Creating new JDBC Connection to [jdbc:hsqldb:file:test/hsqldb/data;shutdown=true] - current autocommit status: true - disabling autocommit - after transaction begin - Exposing JPA transaction as JDBC transaction [SimpleConnectionHandle: org.hsqldb.jdbc.jdbcConnection@1382926] - Bound value [org.springframework.jdbc.datasource.ConnectionHolder@158cc6] for key [org.springframework.jdbc.datasource.DriverManagerDataSource@cf66b] to thread [main] - Bound value [org.springframework.orm.jpa.EntityManagerHolder@7e75d2] for key [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean@cd4544] to thread [main] - Initializing transaction synchronization - Getting transaction for [employee.service.EmployeeViewBuilderService.updateEmployeeView] - opened session at timestamp: 12138839316 - unable to locate HQL query plan in cache; generating (UPDATE employee.pd.Employee emp SET emp.employeeName=? WHERE emp.employeeId =?) ..... Some query interpretation here... ..... - HQL param location recognition took 0 mills (UPDATE employee.pd.Employee emp SET emp.employeeName=? WHERE emp.employeeId =?) - mark transaction for rollback - Completing transaction for [employee.service.EmployeeViewBuilderService.updateEmployeeView] after exception: javax.persistence.TransactionRequiredException: Executing an update/delete query - Applying rules to determine whether transaction should rollback on javax.persistence.TransactionRequiredException: Executing an update/delete query - Winning rollback rule is: null - No relevant rollback rule found: applying default rules - Triggering beforeCompletion synchronization - Initiating transaction rollback - Rolling back JPA transaction on EntityManager [org.hibernate.ejb.EntityManagerImpl@497062] - rollback - re-enabling autocommit - rolled back JDBC Connection - after transaction completion - aggressively releasing JDBC connection - releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)] - after transaction completion - Triggering afterCompletion synchronization - Clearing transaction synchronization - Removed value [org.springframework.orm.jpa.EntityManagerHolder@7e75d2] for key [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean@cd4544] from thread [main] - Removed value [org.springframework.jdbc.datasource.ConnectionHolder@158cc6] for key [org.springframework.jdbc.datasource.DriverManagerDataSource@cf66b] from thread [main] - Closing JPA EntityManager [org.hibernate.ejb.EntityManagerImpl@497062] after transaction - closing session[/CODE] I am struggling with this problem for couple of days but no progress.... :confused: If any body resolved the same problem or you could able to identify the issue please do post your suggestions. Thanks in advance Ravi
  2. Hi Ravindran Loganathan, Always you forgot open the transaction before commit or rollback an entitymanager from entitymanagerfactory you will get this exception. try: // This injects the default persistence unit. @PersistenceContext private EntityManagerFactory emf; // This injects a user transaction object. @Resource private UserTransaction utx; utx.begin(); //entityManager methods.. utx.commit(); //or utx.rollback();
  3. Hi Jao Bosco,

     

    I am also getting same sort of exception. I am using Spring 3.1,JPA and Hibernate. Following is my sample config,code and exception. I have tried different things but nothing worked out. Help is really appreciated.

    hibernate xml:

    <?xml version="1.0" encoding="UTF-8" standalone="no"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop"  xmlns:p="http://www.springframework.org/schema/p" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
    <tx:annotation-driven transaction-manager="transactionManager"/> <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"  p:driverClassName="com.mysql.jdbc.Driver" p:url="jdbc:mysql://instance14684.db.xeround.com:9898/egzist" p:username="rohitkan2000" p:password="generate123"> </bean>        <jee:jndi-lookup id="myJndiDataSource" jndi-name="egzistdb"/>     <!-- Declare a transaction manager--> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> <property name="jpaDialect" ref="jpaDialect" /> <property name="dataSource" ref="myJndiDataSource" /> </bean>  <bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
               <!-- Declare a JPA entityManagerFactory--> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="persistenceXmlLocation" value="classpath*:persistence.xml"></property> <property name="persistenceUnitName" value="hibernatePersistenceUnit" /> <property name="dataSource" ref="myJndiDataSource"/> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" > <property name="showSql" value="true"/> </bean> </property> </bean> </beans>

     

    Service code:

    package com.superi.service.impl;
    import org.springframework.beans.factory.annotation.Autowired;import org.springframework.transaction.annotation.Transactional;
    import com.superi.beans.TemplatesCategory;import com.superi.dao.TemplatesCategoryDao;import com.superi.dao.impl.TemplatesCategoryDaoImpl;import com.superi.service.TemplateCategoryService;
    @Transactionalpublic class TemplateCategoryServiceImpl implements TemplateCategoryService{ @Autowired TemplatesCategoryDao templateCategoryEntity; public TemplateCategoryServiceImpl(){}
    public void setTemplateCategoryEntity( TemplatesCategoryDaoImpl templateCategoryEntity) { this.templateCategoryEntity = templateCategoryEntity; }
    public TemplatesCategory findTemplateCategory(long templateCategoryId) { TemplatesCategory templatesCategory = templateCategoryEntity.findById(templateCategoryId, true); return templatesCategory; } public TemplatesCategory findTemplateCategoryByName(String templateCategoryName) { TemplatesCategory templatesCategory = templateCategoryEntity.findByTemplateCategoryByName(templateCategoryName); return templatesCategory; }
    public TemplatesCategory addTemplateCategory(TemplatesCategory templatesCateogry) throws Exception { TemplatesCategory result = null; result = (TemplatesCategory)templateCategoryEntity.create(templatesCateogry); return result; }
    public boolean updateTemplateCategory(long templateCategoryId, String templateCategoryName, String lastUpdatedBy, String description) throws Exception { return false; }
    @Transactional public boolean deleteTemplateCategory(long templateCategoryId) throws Exception { // TODO Auto-generated method stub return false; }
    }

     

    Dao Impl class:

     

    package com.superi.dao.impl;
    import java.io.Serializable;import java.lang.reflect.ParameterizedType;import java.util.List;
    import javax.persistence.EntityManager;import javax.persistence.LockModeType;import javax.persistence.PersistenceContext;
    import org.springframework.transaction.annotation.Propagation;import org.springframework.transaction.annotation.Transactional;
    import com.superi.dao.GenericDao;import com.superi.dao.IEntity;
    public abstract class GenericDaoImpl<T, ID extends Serializable> implements GenericDao<T, ID> { private EntityManager entityManager; @PersistenceContext public void setEntityManager(EntityManager entityManager) { this.entityManager = entityManager; }
    private Class<T> persistentClass; @SuppressWarnings("unchecked") public GenericDaoImpl(){ this.persistentClass = (Class<T>) ((ParameterizedType) getClass()                 .getGenericSuperclass()).getActualTypeArguments()[0]; } public Class<T> getPersistentClass() {        return persistentClass;    }
    public EntityManager getEntityManager() { return entityManager; }
    public Object create(IEntity entity) { //EntityTransaction et = entityManager.getTransaction(); Object result = false; try{ result = entityManager.merge(entity); flush(); }catch (Exception e) { e.printStackTrace(); } return result; } public boolean update(IEntity entity) { boolean result = false; return result; } public boolean delete(IEntity entity) { boolean result = false; try{ entityManager.remove(entity); flush(); result = true; }catch (Exception e) { result = false; } return result; } public T findById(ID id, boolean lock) {        T entity;        if (lock)            entity = (T) entityManager.find(getPersistentClass(), id, LockModeType.WRITE);        else            entity = (T) entityManager.find(getPersistentClass(), id);         return entity;    } 
        @SuppressWarnings("unchecked") public List<T> findAll() {    return entityManager.createQuery(new StringBuilder("select entity from ")    .append(getPersistentClass().getSimpleName())    .append(" as entity").toString())    .getResultList();    }
    /**     *      */    @Transactional(propagation=Propagation.SUPPORTS)    public void flush() {    entityManager.flush();    }     /**     *      */    public void clear() {    entityManager.clear();    }    }

    Exception I am getting:

    javax.persistence.TransactionRequiredException: no transaction is in progress        at org.hibernate.ejb.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:978)        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:365)        at $Proxy155.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:240)        at $Proxy155.flush(Unknown Source)        at com.superi.dao.impl.GenericDaoImpl.flush(GenericDaoImpl.java:97)        at com.superi.dao.impl.GenericDaoImpl.create(GenericDaoImpl.java:49)        at com.superi.service.impl.TemplateCategoryServiceImpl.addTemplateCategory(TemplateCategoryServiceImpl.java:36)        at com.superi.controller.TemplateCategoryController.addTemplateCategory(TemplateCategoryController.java:40)        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.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213)        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingH

     

    Please help me.