以下の方法では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>
その他の情報は必要ですか? – NKing253
注釈を付けているBean、使用しているプロキシの種類、daoWrapperの実際の動作を定義したSpringの設定。 – Affe
JDKプロキシを使用しているようですね。 GalleryServiceは、そのメソッドを持つインターフェイスを実装して、春がプロキシを生成してトランザクションアドバイスを適用できるようにする必要があります。 – Affe