java - 具有 Activity 事务和连接打开的 LazyInitializationException

标签 java spring hibernate jboss7.x jpa-2.0

我知道这个问题已经被问过很多次了(已经检查了这里和其他网站上的大部分帖子),但我没有解决我的问题。

我的设置是:jpa 2 + hibernate 4 + spring 4 + primefaces + jboss eap 7

问题:我将惰性集合放入另一个 bean 中,但是当我调用 bean 上的 .size() 方法时,它会抛出“LazyInitializationException:未能延迟初始化角色集合:com.pe。 controlLines.data.model.Activity.activityRisks,无法初始化代理 - 无 session ”

我确定在这 LazyInitializationException Within a @Transactional Method 之后我有一个活跃的交易和 http://blog.timmattison.com/archives/2012/04/19/tips-for-debugging-springs-transactional-annotation/所以我 100% 确定当时有交易在运行。

我的实体类:

@Entity
public class Company {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long companyId;

    @Column
    private String name;

    @OneToOne(cascade={CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE})
    private Activity companieActivities;

    @OneToMany
    private Collection<SourceSupervision> sourceSupervisions;

和嵌套类

@Entity
@Indexed
public class Activity {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long activityId;

    @ManyToOne
    @JoinColumn(name="parentActivityId")
    private Activity parent;

    @Column
    @Field(index = Index.YES, analyze = Analyze.YES, store = Store.NO)
    @Analyzer(definition = "searchtokenanalyzer")
    private String name;

    @Column
    @Field(index = Index.YES, analyze = Analyze.YES, store = Store.NO)
    @Analyzer(definition = "searchtokenanalyzer")
    private String description;

    @OneToMany(cascade={CascadeType.PERSIST, CascadeType.REFRESH})
    private Collection<ActivityRisk> activityRisks = new ArrayList<ActivityRisk>();

    @ManyToMany(cascade={CascadeType.PERSIST, CascadeType.REFRESH})
    private Collection<Word> words;

    @ManyToMany
    private Collection<Rol> rolesForActivity;

业务委托(delegate)是这样标注的(业务是从页面 Controller 调用的):

@Component
@Scope("session")
@Transactional
public class SystemConfigurationBussinesDelegate {

获得实体引用的初始化,执行良好。 (这是来自 aboce 类)

private Company currentCompany;

    private Risk currentRisk;

    @PostConstruct
    public void init(){
        //((WordDAO)wordDAO).startIndexer();
        currentCompany = genericDAO.get(Company.class, 1l);
    }

但是在这个方法中

public List<Danger> getDangers(){

        List<Danger> returnValue = new ArrayList<Danger>();
        System.out.println(TransactionSynchronizationManager.isActualTransactionActive());
        Hibernate.initialize(currentCompany.getCompanieActivities());
        currentCompany.getCompanieActivities().getActivityRisks().size();
        for( ActivityRisk aRisk : currentCompany.getCompanieActivities().getActivityRisks() ){
            Risk risk = aRisk.getRisk();
            if(risk == currentRisk){
                returnValue = new ArrayList<Danger>(aRisk.getDangers());
            }
        }
        return returnValue;
    }

sysout 返回 true,因此事务处于 Activity 状态,我可以看到一个打开的数据库连接,Hibernate.inicialize 工作正常,并且调用 currentCompany.getCompanieActivities().getActivityRisks().size();抛出异常。

会不会是上下文有问题或类似的问题?

我的 Spring 配置:

<?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:context="http://www.springframework.org/schema/context"
    xmlns:security="http://www.springframework.org/schema/security"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:util="http://www.springframework.org/schema/util"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-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/aop 
                        http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
                        http://www.springframework.org/schema/util 
                        http://www.springframework.org/schema/util/spring-util-2.5.xsd
                        http://www.springframework.org/schema/jdbc 
                        http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
                        http://www.springframework.org/schema/jee 
                        http://www.springframework.org/schema/jee/spring-jee.xsd">

    <context:component-scan base-package="com.pe.controlLines" />

    <context:annotation-config />
    <context:spring-configured />

    <aop:aspectj-autoproxy proxy-target-class="true"/>

    <jee:jndi-lookup id="myDataSource" jndi-name="java:/ControllinesDS"/>
    <!-- Data Source Declaration -->
    <!-- Session Factory Declaration <bean id="SessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> -->
    <!-- Session Factory Declaration -->
    <bean id="SessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource" />
       <!-- <property name="packagesToScan">
            <list>
                <value>net.javabeat.spring.model</value>
            </list>
        </property>
        <property name="annotatedClasses">
            <list>
                <value>co.com.testTalos.model.Storage</value>
                <value>co.com.testTalos.model.Buyer</value>
                <value>co.com.testTalos.model.Preferences</value>
            </list>
        </property>-->
        <property name="packagesToScan">
            <list>
                <value>com.pe.controlLines.data.model</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.search.default.directory_provider">filesystem</prop>
                <prop key="hibernate.search.default.indexBase">C:/DEVELOPMENT/lucene/indexes</prop>


            </props>
        </property>
    </bean>

    <!-- Enable the configuration of transactional behavior based on annotations -->
    <tx:annotation-driven transaction-manager="txManager"/>

    <!-- Transaction Manager is defined -->
    <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="SessionFactory"/>
    </bean>

</beans>

最佳答案

我认为您的问题与调用 @PostConstruct 中的事务方法有关。通过设计,spring tx 方面在 postconstruct 方法上是/可能不是 Activity 的,因为并非所有 bean 都保证已完成构建。尝试搜索此主题,我记得也曾意外遇到过这个问题,但有很多有用的文章。

从那时起,当我需要在 postconstruct 上进行 tx 时,我首选的替代方法是使用编程事务(请参阅 Spring TransactionTemplate 模式) 使用 ContextRefreshedEvent。请参见以下示例:

@Service
public class MyService implements ApplicationListener<ContextRefreshedEvent> {

  public void onApplicationEvent(ContextRefreshedEvent event) {
    // This method will be executed at context startup or refresh
    // It is guaranteed all beans have finish constructing, hence
    // AOP tx is available
  }
  ...
}

关于java - 具有 Activity 事务和连接打开的 LazyInitializationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26225999/

相关文章:

java - 从非 Spring 类调用 Spring 服务失败

java - 如何使用 HBM 映射创建两列唯一键约束?

hibernate.hbm2ddl.auto=创建不清除现有数据

java - Ecore 建模项目不可用

java.sql.DataTruncation : Data truncation exception and LIKE operator relation

Java mkdir() 不会为字符串对象写入目录,但会为用引号引起来的字符串写入目录

java - Spring Boot Raw WebSocket 设置主体

java - 如何在 struts1 标签库中强制使用 utf8?

java - 无法在 Spring MVC Controller 测试中模拟服务类

hibernate - EntityManager 应该如何在一个很好的解耦的服务层和数据访问层中使用?