2011-01-14 22 views
2

以下の方法ではorg.hibernate.LazyInitializationExceptionがスローされます。その理由を理解する助けに感謝します。 JPA 2/Hibernate & Springを使用しています。SpringトランザクションにもかかわらずLazyInitializationException?

JPA 2/Hibernateは、デフォルトのtransaction永続コンテキストを使用しているため、以下の方法で遅延読み込みを許可しないでください。

@Service 
public class GalleryService { 
    @Transactional(readOnly=true) 
    public Response getGallery(@PathParam("id") int id) { 
     Gallery g = daoWrapper.findById(Gallery.class, id); 
     ... 
     GalleryDto gDto = new GalleryDto(); 
     ... 
     // getImages() returns a collection of 'image' objects. 
     gDto.setImages(g.getImages()); 
     return Response.ok(gDto).build(); 
    } 
} 

daoWrapperエンティティマネージャ方法をラップする便利なクラスです。

@Repository 
public class daoWrapper implements BaseDao { 

    @PersistenceContext(unitName="persistStore") 
    private EntityManager em; 

    @Override 
    public <T,U> T findById(Class<T> entity, U id) { 
     return this.em.find(entity, id); 
    } 
    ... 
} 

アプリケーションコンテキストファイル:

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    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/aop 
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> 

<context:property-placeholder location="classpath:database.properties" /> 
<context:annotation-config /> 
<context:component-scan base-package="com.myapp.services"/> 
<tx:annotation-driven/> 
... 
</beans> 

答えて

3

あり、我々はそれを診断する必要があると思います非常に多くのより多くの情報がありますが、あなたの署名を見て、私の傾斜は、それがないコントローラクラスであるということですプロキシされている。 @Transactionalは、コンテキストを設定する多くの一般的な方法で、Beanファクトリによってプロキシされているクラスでのみ動作します。これにはコントローラクラスは含まれません。

+0

その他の情報は必要ですか? – NKing253

+0

注釈を付けているBean、使用しているプロキシの種類、daoWrapperの実際の動作を定義したSpringの設定。 – Affe

+0

JDKプロキシを使用しているようですね。 GalleryServiceは、そのメソッドを持つインターフェイスを実装して、春がプロキシを生成してトランザクションアドバイスを適用できるようにする必要があります。 – Affe

0

@Affeがあなたの春の構成を求めているのは何ですか? LazyInitializationExceptionが発生している場合は、トランザクションは存在しません。 @Affeが述べたように、プロキシが作成された場合にのみトランザクションが開始されますが、これはあなたの設定に問題がある可能性があります。

0

session.clear(); 

呼び出されたときに、私は同じ問題をキャッチどこか

entity = session.get(...); 

entity.getLazyCollection(); 

の間で非常に単純に、このメソッドを使用しないようにあなたのコードを確認してください。

関連する問題