我遇到了使用EntityManager将元素持久化到数据库的问题.根据我发现的答案,我在DaoJpa中尝试了这4种方法来做这样的事情,但仍然失败了.在这里,我附上了我尝试的四种方式:
控制器部分代码:
@Transactional
SmartProduct smartProduct = new SmartProduct();
smartProduct.setName("Dove Soap");
smartProductDao.persist(smartProduct);
1.
DaoJpa:
@Transactional
public void persist(SmartProduct smartProduct) {
entityManager.persist(smartProduct);
不行!
2.
@Transactional
public void persist(SmartProduct smartProduct) {
entityManager.persist(smartProduct);
entityManager.flush();
Exception I got: no transaction is in progress
3.
@Transactional
public void persist(SmartProduct smartProduct) {
EntityTransaction emTransaction = entityManager.getTransaction();
emTransaction.begin();
entityManager.persist(smartProduct);
emTransaction.commit();
entityManager.close();
Exception I got:
Not allowed to create transaction on shared EntityManager – use Spring
transactions or EJB CMT instead
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();
Exception I got:
The application must supply JDBC connections
有人可以帮我解决问题吗?提前谢谢了!
非常感谢JustinKSU的帮助.我在Spring上下文中添加了注释,然后它就解决了!
这是我的Spring上下文的上一个版本:
factorybean" id="entityManagerFactory">
加了之后
有用:
factorybean" id="entityManagerFactory">
最佳答案