JQPL更新查询,无需使用主键即可更新实体 [英] JQPL Update Query to update entity without using the primary key

查看:94
本文介绍了JQPL更新查询,无需使用主键即可更新实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个简单的问题,但是我试图找出是否有一种方法可以创建一个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:

通常,仅应执行批量更新和删除操作 在新的持久性上下文中或在获取之前的事务中 或访问状态可能会受到此类影响的实体 操作.

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.

这篇关于JQPL更新查询,无需使用主键即可更新实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆