我有一個JPA實體與一個OneToMany關係延遲加載。
我使用Sping Data JPA來檢索實體,並且在我的服務的一個方法中,我需要檢索已初始化的列表,因爲我需要在JSP中打印它。 我所做的是:服務層懶惰的關係初始化
@Override
@Transactional(readOnly=true, propagation=Propagation.REQUIRED)
public User retrieveUser(String username) {
final User user = userRepository.findByUsername(username);
user.getFriends().size(); //This line throws a LazyInitializationException
return user;
}
但這種方法行不通,也不是優雅的,我怎麼能實現呢?
唯一的例外是:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: it.nikeconsulting.chirp.domain.User.follows, no session or session was closed
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:489)
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:447)
at org.hibernate.collection.internal.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:139)
at org.hibernate.collection.internal.PersistentBag.size(PersistentBag.java:242)
at it.nikeconsulting.chirp.domain.service.ChirpUserServiceImpl.retrieveUser(ChirpUserServiceImpl.java:26)
我的context.xml是:
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="it.nikeconsulting.chirp.domain" />
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
</bean>
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
<property name="nestedTransactionAllowed" value="true" />
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" id="jpaVendorAdapter">
<property name="showSql" value="true" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect"/>
</bean>
你爲我節省了很多時間。我有同樣的問題。我正在掃描我的MVCConfig文件中的服務。 – Ramps 2014-11-19 18:58:53