JPA - 创建不存在实体? [英] JPA - create-if-not-exists entity?
问题描述
在我的JPA / Hibernate应用程序中有几个映射对象。在网络上我接收到表示这些对象的更新的数据包,或者可能实际上完全代表新的对象。
I have several mapped objects in my JPA / Hibernate application. On the network I receive packets that represent updates to these objects, or may in fact represent new objects entirely.
我想写一个类似
<T> T getOrCreate(Class<T> klass, Object primaryKey)
一个存在于数据库中的pk primaryKey,否则创建该类的一个新对象,并保存并返回。
that returns an object of the provided class if one exists in the database with pk primaryKey, and otherwise creates a new object of that class, persists it and returns it.
对象将在一个事务中更新其所有字段。
The very next thing I'll do with the object will be to update all its fields, within a transaction.
在JPA中有一个惯用的方式来做到这一点,还是有更好的方法来解决我的问题?
Is there an idiomatic way to do this in JPA, or is there a better way to solve my problem?
推荐答案
- 创建一个EntityManager实例(让我们称之为em
- 调用em.find(Object pk)
- 调用tx.begin()
-
- 如果find()返回一个非空的实体引用, 。将更改应用于返回的实体,然后调用em.merge(Object entity)。
- 如果find()返回空引用,则该PK在数据库中不存在。创建一个新实体,然后调用em.persist(Object newEntity)。
- Create an EntityManager instance (let's call it "em"), unless you already have an active one
- Create a new transaction (let's call it "tx")
- Call em.find(Object pk)
- Call tx.begin()
- If find() returned a non-null entity reference then you need to do an update. Apply your changes to the returned entity and then call em.merge(Object entity).
- if find() returned a null reference, then that PK does not exist in the database. Create a new entity and then call em.persist(Object newEntity).
这篇关于JPA - 创建不存在实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!