【问题标题】:JPQL Query Bulk UPDATE SET on an ElementCollection fieldElementCollection 字段上的 JPQL 查询批量更新集
【发布时间】:2013-11-27 15:41:17
【问题描述】:

我有以下想要更新的 JPA 实体:

@Entity(name = "EmployeeImpl")
@Table(name = "EmployeeImpl")
public class EmployeeImpl {
  @Id
  @Column(name = "employeeId")
  @GeneratedValue(strategy = GenerationType.AUTO)
  private long id;

  @ElementCollection
  private List<String> phonenumber;
}

我以为我像这样使用namedQuery

@NamedQuery(name = "updateEmployee",
    query = "Update EmployeeImpl e SET e.phonenumber :number WHERE e.id = :id")

但这不起作用:Exception Description: Error compiling the query [updateEmployee: Update EmployeeImpl e SET e.phonenumber = :number WHERE e.id = :id], line 1, column 28: invalid access of attribute [phonenumber] in SET clause target [e], only state fields and single valued association fields may be updated in a SET clause.

问题是,如何更新@ElementCollection?如果可能的话,我想用 jpql 查询来做。

【问题讨论】:

  • 您要更新整个号码列表还是简单地添加一个号码?
  • 我对两者都感兴趣。我发布的查询应该用新值替换所有数字。

标签: jpa jpql bulkupdate


【解决方案1】:

不,这在 JPQL 中是不可能的。正如 kostja 所说:消息说得很清楚,而且根据 JPA 规范,“4.10 批量更新和删除操作”一章,您可以只更新状态字段和单值对象字段。

这些操作的语法如下:

update_statement ::= update_clause [where_clause]
update_clause ::= UPDATE entity_name [[AS] identification_variable]
                  SET update_item {, update_item}*

update_item ::= [identification_variable.]{state_field | single_valued_object_field} =    new_value

new_value ::=
scalar_expression |
simple_entity_expression |
NULL

怎么办?

可能最简洁的方法就是获取实体并添加/替换电话号码,尽管您也可以随时使用Native Queries 执行此操作,即 kostja 所说的 SQL 查询。

【讨论】:

    【解决方案2】:

    错误消息中说明了失败的原因。您不能对实体的非奇异属性使用批量更新,因为它们存储在不同的表中。

    你是怎么做的呢?您更新集合表。

    集合表的默认表名是&lt;parent_entity&gt;_&lt;field_name&gt;。所以你感兴趣的表应该命名为EmployeeImpl_phonenumber。默认情况下,EmployeeImpl(外键)的id 列应命名为EmployeeImpl_id

    编辑 我最初发布的内容在 JPQL 中无效。您可能想改用本机查询。它很简单,所以它应该是可移植的:

    本机查询可能如下所示:

    UPDATE EmplyeeImpl_phonenumber 
    SET phonenumber = ? 
    WHERE employeeimpl_id = ?
    

    【讨论】:

    • 不,这是我的想法。如果它不起作用,我将删除答案。但你可能是对的,我正在混合 JPQL 和原生 SQL。
    • 编译该查询时出现错误:Unknown entity type [EmployeeImpl_phonenumber] 我想我无法更新不是实体的东西,至少不是那样。
    • 对了,那你可能肯定会使用原生SQL
    • 我想我做不到。这必须至少在 H2 和 PostgreSQL 上工作。
    猜你喜欢
    • 2014-01-12
    • 2014-03-22
    • 2016-08-17
    • 2011-07-07
    • 2020-05-03
    • 1970-01-01
    • 2021-08-25
    • 2013-04-01
    • 2023-04-02
    相关资源
    最近更新 更多