1

我有以下要更新的 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 查询来做。

4

2 回答 2

3

不,这在 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 查询。

于 2013-11-27T16:05:02.463 回答
2

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

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

集合表的默认表名是<parent_entity>_<field_name>。所以你感兴趣的表应该命名为EmployeeImpl_phonenumber. (外键)的idEmployeeImplEmployeeImpl_id默认命名。

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

本机查询可能如下所示:

UPDATE EmplyeeImpl_phonenumber 
SET phonenumber = ? 
WHERE employeeimpl_id = ?
于 2013-11-27T15:50:22.827 回答