英文:
JPA clear entity manager
问题
我有以下代码,我正在持久化一个自动生成的产品ID。
在持久化后,我调用了clear(),它应该清除实体上下文。
但我在事务提交后在数据库中看到了一条记录。
问题:当我已经清除了上下文,为什么JPA还会插入一条记录?
entityManager.getTransaction().begin();
Product product = new Product("洗衣机3", 1100l);
entityManager.merge(product);
entityManager.clear();
entityManager.getTransaction().commit();
英文:
I have below code where i am persisting a product whose id is auto generated.
after persist(), i am calling clear() which should clear the entity context.
But i see there is a record in the database after the transaction is committed.
Question: when i have cleared the context, how come jpa is inserting a recored?
entityManager.getTransaction().begin();
Product product = new Product("washing machine3",1100l);
entityManager.merge(product);
entityManager.clear();
entityManager.getTransaction().commit();
答案1
得分: 4
clear()
方法只会清除实体管理器中的所有受管实体。它不会撤销已经刷新到数据库的实体更改。与这些实体更改相关的SQL已经应用到数据库上,只是等待数据库事务提交才能真正生效。
现在,当你合并一个新的产品时,Hibernate 实际上会将相关的插入SQL刷新到数据库中。(根据ID生成策略而定,但如果ID配置为自增,它应该会立即刷新插入SQL到数据库中)。这就是为什么即使在此之后清除实体管理器,插入SQL已经在数据库中应用的原因。
如果你真的不想插入新产品,你应该回滚事务:
entityManager.getTransaction().rollback();
英文:
clear()
only clear all the managed entities in the entity manager. It will not undo the entities changes that are already flushed to the DB . The SQL related to those entities changes are already applied on DB and just wait for the DB transaction to commit in order to really take effect.
Now when you merge a new product , Hibernate actually flush the related insert SQL to the DB. (Have impression that depends on the ID generation strategy actually , but if the ID is configured as auto increment , it should flush the INSERT SQL to DB immediately) That 's why even you clear the entity manager after that , the insert SQL is already applied at DB.
If you really want to not insert a new product , you should rollback the transaction :
entityManager.getTransaction().rollback();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论