简体   繁体   English

JQPL更新查询,无需使用主键即可更新实体

[英]JQPL Update Query to update entity without using the primary key

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. 这可能是一个简单的问题,但是我试图找出是否有一种方法可以创建一个JPQL更新查询,该查询将允许我使用不是主键的唯一列标识符来更新单个持久化实体。

Say I have and entity like the following: 说我有以下实体:

@Entity
public class Customer {
    @ID
    private Long id;
    @Column
    private String uniqueExternalID;
    @Column
    private String firstname;
    ....
}

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. 使用具有id值集的Customer更新此实体很容易,但是,id喜欢使用uniqueExternalId更新此客户实体,而无需预先查询本地实体并合并更改或手动构造jpql查询,手动输入其中的字段。

Something like 就像是

UPDATE Customer c SET c = :customer WHERE c.uniqueExternalId = :externalId

Is something like this possible in JQPL? 在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. 请注意,您将必须明确定义每个更新的属性。

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: 此外,如果您使用乐观锁定,请考虑通过批量更新增加实体的@Version字段:

 UPDATE Customer c SET c.name = :name, c.version = c.version + 1  WHERE c.uniqueExternalId = :externalId

EDIT: The JPA 2.0 spec advises in § 4.10: 编辑:JPA 2.0规范在第4.10节中建议:

In general, bulk update and delete operations should only be performed within a transaction in a new persistence context or before fetching or accessing entities whose state might be affected by such operations. 通常,批量更新和删除操作仅应在新的持久性上下文中的事务内执行,或者应在获取或访问其状态可能受此类操作影响的实体之前执行。

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

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