尽管我正在使用@Transactional注释,但“无法初始化代理 - 无会话”

时间:2013-04-19 16:21:46

标签: spring hibernate transactions lazy-initialization

我正在使用Spring 3.1.1.RELEASE和Hibernate 4.1.0.Final。我得到了“无法初始化代理 - 无会话”异常,尽管事实上我正在将相关方法调用包装在@Transactional注释中。这是我的方法......

@Service("teacherImportService")
public class TeacherImportServiceImpl extends AbstractmyprojectService 
{
    …
    @Transactional
    @Override
    public void saveUserObject(final JsonObject jsonData)  
    {
        …
        final myprojectOrganization myprojectOrg = myprojectOrgDao.findBymyprojectOrgId(myprojectSchoolId);
        final Organization school = myprojectOrg != null ? myprojectOrg.getOrg() : null;
            …
        final Address address = new Address();
        address.setState(school.getState());    // error occurs here

我还需要做些什么来保证交易发生?我已经包含了“< tx:annotation-driven />”在我的应用程序上下文中,我在下面包含

<context:component-scan base-package="org.mainco.subco" />
...
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${test.mysql.dataSource.driverClassName}" />
    <property name="url" value="${test.mysql.dataSource.url}" />
    <property name="username" value="${test.mysql.db.user}" />
    <property name="password" value="${test.mysql.db.password}" />
</bean>

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="packagesToScan" value="org.mainco.subco" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
    </property>
    <property name="dataSource" ref="dataSource"/>
    <property name="jpaPropertyMap" ref="jpaPropertyMap" />
</bean>

<util:map id="jpaPropertyMap">
    <entry key="hibernate.show_sql" value="true" />
    <entry key="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" /> 
    <entry key="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.EhCacheRegionFactory"/>
    <entry key="hibernate.cache.provider_class" value="org.hibernate.cache.EhCacheProvider"/>
    <entry key="hibernate.cache.use_second_level_cache" value="true" />
    <entry key="hibernate.cache.use_query_cache" value="false" />
    <entry key="hibernate.generate_statistics" value="true" />
</util:map>

<bean id="sharedEntityManager" class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
   <property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>

<tx:annotation-driven />

<jdbc:initialize-database data-source="dataSource">
    <jdbc:script location="classpath:truncate_tables.sql" />
    <jdbc:script location="classpath:db-test-data.sql" />
</jdbc:initialize-database>

这是异常的完整堆栈跟踪...

org.hibernate.LazyInitializationException: could not initialize proxy - no Session
    at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:149)
    at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:195)
    at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
    at org.mainco.subco.organization.domain.Organization_$$_javassist_30.getState(Organization_$$_javassist_30.java)
    at org.mainco.subco.myproject.service.TeacherImportServiceImpl.saveUserObject(TeacherImportServiceImpl.java:101)
    at org.mainco.subco.myproject.service.AbstractmyprojectService.saveUsers(AbstractmyprojectService.java:226)
    at org.mainco.subco.myproject.service.AbstractmyprojectService$$FastClassByCGLIB$$d080e416.invoke(<generated>)
    at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
    at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:618)
    at org.mainco.subco.myproject.service.TeacherImportServiceImpl$$EnhancerByCGLIB$$a06c7e9f.saveUsers(<generated>)
    at org.mainco.subco.myproject.service.TeacherImportServiceTest.testSaveTeachers(TeacherImportServiceTest.java:46)
    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:83)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    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:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    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)

3 个答案:

答案 0 :(得分:6)

也许您忘了将交易注释添加到AbstractmyprojectService.saveUsers()

请注意,内部调用永远不会被代理,因此流程:

 TeacherImportServiceTest.testSaveTeachers() -> 
 AbstractmyprojectService.saveUsers() -> 
 TeacherImportServiceImpl.saveUserObject()

如果AbstractmyprojectService.saveUsers()根本不是交易性的,则不会是交易性的。

修改

阅读完评论后,我看到了三个解决方案:

  • saveUsers()方法解压缩到辅助类

非常简单,重构代码以将Tx方法保留在一个类中,并通过组合从另一个类中使用它。

  • 使用saveUserObject() 中的程序化交易。
例如,注入txManager和

public void saveUserObject() {
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        TransactionStatus status = txManager.getTransaction(def);
        try {
          // the code
        }
        catch (Exception ex) {
          txManager.rollback(status);
          throw ex;
        }
        txManager.commit(status);
    }
  • 使用AspectJ代替Spring AOP。(我认为此选项仅对此问题过于复杂。)

使用AspectJ,您可以使用Aspect AnnotationTransactionAspect

替换AOP Proxies

使用<tx:annotation-driven mode="aspectj"/>并选择编织方法(编译或加载时间)。

有关加载时间的编织,请参阅http://static.springsource.org/spring/docs/3.0.5.RELEASE/reference/aop.html#aop-aj-ltw

编译时使用maven进行编织,请参阅Spring / @Transactional with AspectJ is totally ignored

答案 1 :(得分:0)

在你的应用程序上下文XML中,我没有看到组件扫描配置会让Spring管理立体声类型注释bean类[即,使用 @Service 注释的类, @Repository @Component ]

只需为以下任何类添加包扫描,如下例所示:

<context:component-scan base-package="some.package.where.stereotypedclassesexist"/>

关于spring托管组件的类路径扫描,Spring文档参考here

HTH。

答案 2 :(得分:0)

这可能与proxy implementation pattern有关。尝试将saveUserObject提取到界面:

public class TeacherImportServiceImpl extends AbstractmyprojectService implements SomeInterface {

    @Transactional
    @Override
    public void saveUserObject(final JsonObject jsonData)  {
        ...
    }

}

public interface SomeInterface {
   void saveUserObject(JsonObject jsonData);
}

您也可以尝试使用CGLIB进行基于类的代理:

<tx:annotation-driven proxy-target-class="true" />