我遇到了使用EntityManager将元素持久保存到数据库的问题。根据我发现的答案,我在DaoJpa中尝试了这4种方法来执行此操作,但仍然失败。在这里,我附上了我尝试过的四种方法:
控制器部分中的代码:
@Transactional SmartProduct smartProduct = new SmartProduct(); smartProduct.setName("Dove Soap"); smartProductDao.persist(smartProduct);
1.道霸:
@Transactional public void persist(SmartProduct smartProduct) { entityManager.persist(smartProduct);
不起作用!
2。
@Transactional public void persist(SmartProduct smartProduct) { entityManager.persist(smartProduct); entityManager.flush();
我得到的例外:没有交易在进行中
3。
@Transactional public void persist(SmartProduct smartProduct) { EntityTransaction emTransaction = entityManager.getTransaction(); emTransaction.begin(); entityManager.persist(smartProduct); emTransaction.commit(); entityManager.close();
我得到的异常:不允许在共享的EntityManager上创建事务-使用Spring事务或EJB CMT代替
4。
@Transactional public void persist(SmartProduct smartProduct) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistenceUnit"); EntityManager em = emf.createEntityManager(); EntityTransaction etx = em.getTransaction(); etx.begin(); em.persist(smartProduct); etx.commit(); em.close(); emf.close();
我得到的异常:应用程序必须提供JDBC连接
有人可以帮我解决问题吗?提前谢谢了!
非常感谢JustinKSU的帮助。我在Spring上下文中添加了注释,然后解决了!这是我的Spring上下文的先前版本:
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> <tx:annotation-driven mode="aspectj" transaction-manager="transactionManager" /> <bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory"> <property name="persistenceUnitName" value="persistenceUnit" /> <property name="dataSource" ref="dataSource" /> </bean>
加入后
<tx:annotation-driven />
有用:
<tx:annotation-driven /> <bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> <tx:annotation-driven mode="aspectj" transaction-manager="transactionManager" /> <bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory"> <property name="persistenceUnitName" value="persistenceUnit" /> <property name="dataSource" ref="dataSource" /> </bean>
要在您的Spring上下文中启用@Transactional,您应该具有以下内容:
适合您的Spring版本:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
启用注释:
声明您的事务管理器注入实体管理器:
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean>