问题描述
这可能是一个简单的问题,但是我试图找出是否有一种方法可以创建一个JPQL更新查询,该查询将允许我使用一个唯一的,而不是唯一的列标识符来更新单个持久化实体.主键.
This may be a simple question, but I'm trying to find out if there is a way that I can create a JPQL update query that would allow me to update a single Persisted Entity using a unique column identifier that is not the primary key.
说我拥有和如下实体:
@Entity
public class Customer {
@ID
private Long id;
@Column
private String uniqueExternalID;
@Column
private String firstname;
....
}
使用设置了id值的Customer更新此实体很容易,但是,id喜欢使用uniqueExternalId更新此Customer实体,而无需预先查询本地实体并合并更改或手动构造jpql手动查询其中的所有字段.
Updating this entity with a Customer that has the id value set is easy, however, id like to update this customer entity using the uniqueExternalId without having to pre-query for the local entity and merge the changes in or manually construct a jpql query with all the fields in it manually.
类似
UPDATE Customer c SET c = :customer WHERE c.uniqueExternalId = :externalId
在JQPL中有可能发生这种情况吗?
Is something like this possible in JQPL?
推荐答案
您无法按照您描述的确切方式进行操作-通过传递实体引用,但是可以使用批量查询来达到相同的效果.
You cannot do it in the exact way you describe - by passing an entity reference, but you can use bulk queries to achieve the same effect.
UPDATE Customer c SET c.name = :name WHERE c.uniqueExternalId = :externalId
请注意,您将必须明确定义每个更新的属性.
Please note that you will have to explicitly define each updated attribute.
重要的是要注意,批量查询会绕过持久性上下文.在持久性上下文中管理的实体实例将不会反映对由批量更新更改的记录的更改.此外,如果您使用乐观锁定,请考虑使用批量更新来增加实体的@Version
字段:
It is important to note that bulk queries bypass the persistence context. Entity instances that are managed within the persistence context will not reflect the changes to the records that are changed by the bulk update. Further, if you use optimistic locking, consider incrementing the @Version
field of your entities with the bulk update:
UPDATE Customer c SET c.name = :name, c.version = c.version + 1 WHERE c.uniqueExternalId = :externalId
JPA 2.0规范在第4.10节中提供建议:
The JPA 2.0 spec advises in § 4.10:
这篇关于JQPL更新查询,无需使用主键即可更新实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!