在ElementCollection字段上的JPQL查询批量更新设置

时间:2013-11-27 15:41:17

标签: jpa jpql bulkupdate

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

2 个答案:

答案 0 :(得分: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查询。 / p>

答案 1 :(得分:2)

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

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

集合表的默认表名是<parent_entity>_<field_name>。因此,您感兴趣的表应命名为EmployeeImpl_phonenumber。默认情况下,id(外键)的EmployeeImpl列应命名为EmployeeImpl_id

编辑我最初发布的内容在JPQL中无效。您可能希望使用本机查询。它很简单,所以它应该是便携式的:

原生查询可能如下所示:

UPDATE EmplyeeImpl_phonenumber 
SET phonenumber = ? 
WHERE employeeimpl_id = ?