Announcement Announcement Module
Collapse
No announcement yet.
Spring/Hibernate Annotations failing to create transactions Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Spring/Hibernate Annotations failing to create transactions

    Hello everyone,

    I'm trying to setup a new project that uses Spring Annotations and Hibernate to manage transactions, but I seem to be having some problems. (see below

    If anyone can shed any light on this, I'd really appreciate it!!

    Cheers,
    Adam

    Code:
    org.hibernate.HibernateException: persist is not valid without active transaction
    	at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:297)
    	at $Proxy20.persist(Unknown Source)
    	at uk.co.company.product.persistance.hibernate.AbstractTemp1DAO.save(AbstractTemp1DAO.java:21)
    	at uk.co.company.product.persistance.hibernate.Temp1DAOImpl.save(Temp1DAOImpl.java:1)
    	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.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:307)
    	at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182)
    	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149)
    	at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106)
    	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
    	at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
    	at $Proxy13.save(Unknown Source)
    	at uk.co.company.product.business.spring.UserServiceImpl.authenticate(UserServiceImpl.java:42)
    	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.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:307)
    	at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182)
    	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149)
    	at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106)
    	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
    	at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
    	at $Proxy15.authenticate(Unknown Source)
    	at uk.co.company.product.SpringTest.testUserService(SpringTest.java:25)
    	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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    	at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
    	at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
    	at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
    	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240)
    	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
    	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    	at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    	at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    	at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180)
    	at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
    	at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

  • #2
    Here is a short JUnit text I wrote to investigate the problem:


    JUnit Test:

    Code:
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(
    	locations = {"file:src/conf/applicationContext.xml"},
    	inheritLocations = true
    )
    @TestExecutionListeners({DependencyInjectionTestExecutionListener.class})
    final public class SpringTest{
        @Autowired
        private UserService userService;
    
        @Test
        public void testUserService() {
           Assert.assertTrue(userService.authenticate("Admin", "password"));
        }
    }

    applicationContext.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: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-2.5.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
        "
        default-autowire="byType"
        default-lazy-init="false"
    >
    	<bean id="wicketApplication" class="uk.co.company.product.presentation.wicket.app.WicketApplication" />
    
        <bean id="placeholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" autowire="byName">
            <property name="ignoreUnresolvablePlaceholders" value="false" />
            <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
            <property name="ignoreResourceNotFound" value="false" />
            <property name="locations"><list>
                <value>classpath*:/application.properties</value>
            </list></property>
        </bean>
        
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" autowire="byName">
            <property name="driverClassName"><value>${jdbc.driver}</value></property>
            <property name="url"><value>${jdbc.url}</value></property>
            <property name="username"><value>${jdbc.username}</value></property>
            <property name="password"><value>${jdbc.password}</value></property>
        </bean>
    
        <tx:annotation-driven transaction-manager="transactionManager" />
    
        <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" autowire="byName">
            <property name="sessionFactory" ref="sessionFactory" />
        </bean>
        
        <!--<bean id="interceptor" class="com.mycompany.hibernate.HibernateInterceptor">
        </bean>-->
    
        <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" autowire="byName">
            <property name="dataSource" ref="dataSource" />
            <property name="hibernateProperties">
                <props>
                	<!-- GENERAL -->
                    <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                    <prop key="hibernate.show_sql">true</prop>
                    <prop key="hibernate.show_sql">hibernate.format_sql</prop>
                    <prop key="hibernate.default_schema">zen_template</prop>
                    <prop key="hibernate.max_fetch_depth">2</prop>
                    <!-- <prop key="hibernate.default_batch_fetch_size">16</prop> -->
                    <prop key="hibernate.default_entity_mode">pojo</prop>
                    <prop key="hibernate.order_updates">true</prop>
                    <prop key="hibernate.generate_statistics">true</prop>
                    <prop key="hibernate.use_identifier_rollback">true</prop>
                    <prop key="hibernate.current_session_context_class">thread</prop>
                    <prop key="hibernate.use_outer_join">true</prop>
                    <!-- JDBC -->
                    <!-- <prop key="hibernate.jdbc.batch_size">20</prop> -->
                    <!-- <prop key="hibernate.jdbc.batch_versioned_data">true</prop> -->
                    <prop key="hibernate.jdbc.use_streams_for_binary">true</prop>
                    <prop key="hibernate.jdbc.use_get_generated_keys">true</prop>
    				<!-- CONNECTION -->
                    <prop key="hibernate.connection.isolation">8</prop><!-- TRANSACTION_SERIALIZABLE -->
    				<prop key="hibernate.connection.autocommit">false</prop>
                    <prop key="hibernate.connection.pool_size">5</prop>
                    <!-- CACHE -->
                    <!-- <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop> -->                
                    <!-- <prop key="hibernate.cache.use_minimal_puts">true</prop> -->
                    <!-- <prop key="hibernate.cache.use_query_cache">true</prop> -->
                 	<!-- MISCELLANEOUS -->
                 	<prop key="hibernate.bytecode.use_reflection_optimizer">true</prop>
                    <prop key="hibernate.cglib.use_reflection_optimizer">true</prop>
                    <!-- <prop key="hibernate.bytecode.provider">cglib</prop> -->
                    <!-- <prop key="hibernate.query.substitutions">true</prop> -->
                </props>
            </property>
            <!--<property name="entityInterceptor">
                <ref bean="interceptor" />
            </property>-->
            <property name="packagesToScan"><list>
            	<value>uk.co.company.product</value>
            </list></property>
        </bean>
     	<context:component-scan base-package="uk.co.company.product" />
     	<context:annotation-config/> 
    </beans>

    Comment


    • #3
      Also, here is the Service:

      Code:
      @Service
      public class UserServiceImpl extends _AbstractService implements UserService{
      
      	final private TestUserService testUserService = new TestUserService();
      
      	@Autowired
      	private Temp1DAO temp1DAO;
      	@Required @Override
      	final public void setTemp1DAO(final Temp1DAO temp1dao){
      		temp1DAO = temp1dao;
      	}
      
      	public UserServiceImpl(){
      		super();
      		//InjectorHolder.getInjector().inject(this);//<-- VERY IMPORTANT to get Spring DI to work.
      	}
      
      	/* (non-Javadoc)
      	 * @see uk.co.company.product.business.spring.UserService#authenticate(java.lang.String, java.lang.String)
      	 */
      	@Override
      	@Transactional(propagation=Propagation.REQUIRED)
      	final public boolean authenticate(final String userName, final String password){
      		final Temp1 temp1 = new Temp1();
      		temp1.setValue(userName);
      		temp1DAO.save(temp1);
      		return testUserService.authenticate(userName, password);
      	}
      
      	/* (non-Javadoc)
      	 * @see uk.co.company.product.business.spring.UserService#getRoles(java.lang.String, boolean)
      	 */
      	@Override
      	@Transactional
      	final public Roles getRoles(final String userName, final boolean signedIn){
      		return testUserService.getRoles(userName, signedIn);
      	}
      }

      Comment


      • #4
        Fix your configuration. (Also this question is answered numerous times before).

        Short answer: NEVER mess around with the 'hibernate.current_session_context_class' when using spring (unless you use JTA), it will break proper spring based tx management.

        Comment

        Working...
        X