bernate时如何解决LazyInitializationEx

bernate时如何解决LazyInitializationEx

本文介绍了使用JPA和Hibernate时如何解决LazyInitializationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为想要使用延迟初始化的客户开发一个项目.使用默认延迟加载模式映射类时,它们总是会出现延迟初始化异常".

I am working on a project for a customer who wants to use lazy initialization.They always get "lazy initialization exception" when mapping classes with the default lazy loading mode.

@JoinTable(name = "join_profilo_funzionalita", joinColumns = {@JoinColumn(name =    "profilo_id", referencedColumnName = "profilo_id")}, inverseJoinColumns = {@JoinColumn(name = "funzionalita_id", referencedColumnName = "funzionalita_id")})
//@ManyToMany(fetch=FetchType.EAGER) - no exceptions if uncommented
@ManyToMany
private Collection<Funzionalita> funzionalitaIdCollection;

是否有使用 JPA 类的标准模式来避免此错误?

Is there a standard pattern using JPA classes to avoid this error?

欢迎提供代码片段,非常感谢您抽出宝贵时间.

Snippets are welcome, thanks a lot for your time.

推荐答案

Hibernate 4.1.6 终于解决了这个问题:https://hibernate.atlassian.net/browse/HHH-7457

Hibernate 4.1.6 finally solves this issue: https://hibernate.atlassian.net/browse/HHH-7457

你需要设置hibernate-property hibernate.enable_lazy_load_no_trans=true

You need to set the hibernate-property hibernate.enable_lazy_load_no_trans=true

以下是在 Spring 中执行此操作的方法:

Here's how to do it in Spring:

<bean id="entityManagerFactory"
      class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="myDataSource"/>
    <property name="packagesToScan" value="com.mycompany.somepackage"/>
    <property name="jpaVendorAdapter" ref="hibernateVendorAdapter"/>
    <property name="jpaDialect" ref="jpaDialect"/>
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.enable_lazy_load_no_trans">true</prop>
        </props>
    </property>
</bean>

瞧;现在,在休眠会话之外导航域模型时,您不必担心 LazyInitializationException(JPA-speak"中的持久性上下文)

Voila; Now you don't have to worry about LazyInitializationException while navigating your domain-model outside of a hibernate-session (persistence-context in "JPA-speak")

这篇关于使用JPA和Hibernate时如何解决LazyInitializationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 21:52