简体   繁体   English

JPA不是持久实体

[英]JPA not persisting entity

I am trying to save to database changes made to a detached entity. 我正在尝试将对独立实体所做的更改保存到数据库中。 The object of the entity is passed to the function by argument (named as data): 实体的对象通过参数(称为数据)传递给函数:

private boolean generate(CommonGameData data) {
        boolean result = true;
        EntityManager em = HibernateUtil.currentEntityManager();
        try {
            em.getTransaction().begin();

            em.merge(data);
            em.flush();
            ...some changes to data object...
            em.persist(data);
            em.flush();
            em.getTransaction().commit();

    } catch (Exception ex) {
        ...
        return false;
    }
        return true;
}

As I have read if I am using the detached entity, I should call merge first. 如我所阅读的,如果我使用的是分离实体,则应首先调用merge。 But after commit is done successfully, I don't see any changes in database. 但是在成功完成提交之后,我看不到数据库中的任何更改。 Where is the mistake? 错误在哪里?

As you do not save a new entity (from your comment), you do not need a call to persist() . 由于您没有保存新实体(根据您的评论),因此不需要调用persist() Also I do not see any reasons to make 'some changes' after calling merge() , so I called merge() after making those changes. 另外,在调用merge() ,我看不出有任何理由进行“某些更改”,因此在进行了这些更改之后,我调用了merge()

So, try the following: 因此,请尝试以下操作:

    em.getTransaction().begin();

    ...some changes to data object...
    em.merge(data);
    em.flush();

    em.getTransaction().commit();

Also very important: if you reuse the EntityManager from the a ThreadLocal variable, you should take care of things like failed past transactions (at least clear it + maybe close it). 同样非常重要:如果您从ThreadLocal变量重用EntityManager ,则应该注意过去的事务失败(至少清除它+可能关闭它)。 Also if the bug still persists, try recreating an entityManager. 另外,如果错误仍然存​​在,请尝试重新创建一个entityManager。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM