加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

java – EntityManager不能使用persist将元素保存到数据库

发布时间:2020-12-15 01:36:50 所属栏目:大数据 来源:网络整理
导读:我遇到了使用EntityManager将元素持久化到数据库的问题.根据我发现的答案,我在DaoJpa中尝试了这4种方法来做这样的事情,但仍然失败了.在这里,我附上了我尝试的四种方式: 控制器部分代码: @Transactional SmartProduct smartProduct = new SmartProduct(); s

我遇到了使用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上下文的上一个版本:

加了之后

有用:

最佳答案
要在Spring上下文中启用@Transactional,您应该具有以下内容:

适合您的Spring版本:

启用注释:

声明您的事务管理器注入您的实体管理器:

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读