0
我想使用JPA與Spring MVC持久化實體列表,但收到以下錯誤。錯誤持久化實體列表 - java.lang.IllegalStateException:不允許在共享EntityManager上創建事務
java.lang.IllegalStateException:不允許在共享的EntityManager創建事務 - 使用Spring的事務或EJB CMT,而不是
我試着用搜索引擎的答案,但解決辦法並不適用於我的情況。
下面是我的服務實現中的方法。
@Override
@Transactional
public void saveTemporaryRecords(List<TemporaryRecord> temporaryRecords) {
for (TemporaryRecord temporaryRecord : temporaryRecords) {
try {
temporaryRecordDao.persist(temporaryRecord);
} catch (Exception e) {
e.printStackTrace();
}
}
}
的temporaryRecordDao接口和它的實現沒有任何方法,它們擴展AbstractDao的執行下面的方法:
@PersistenceContext
protected EntityManager em;
@Override
public void persist(Entity entity) throws Exception {
if (entity == null) {
throw new Exception("Entity is null");
}
try {
em.persist(entity);
} catch (Exception ex) {
ex.getMessage();
em.getTransaction().rollback();
em.close();
}
}
調度-servlet.xml中有以下相關配置:
<!-- Configure Entity Manager -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource"
p:packagesToScan="hu.beczdev.webbudgetapp.model">
<property name="jpaVendorAdapter">
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:databasePlatform="org.hibernate.dialect.MySQL5Dialect" p:showSql="true" />
</property>
</bean>
<!-- Configure TransactionManager -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>