JPQL Query Bulk UPDATE SET on an ElementCollection field

浪尽此生 提交于 2019-12-11 12:09:45

问题


I have the following JPA Entity I want to update:

@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;
}

I thought I use a namedQuery like so

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

But that doesn't work: 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.

Question is, how do I update an @ElementCollection? If it's possible i'd like to do it with a jpql query.


回答1:


No, that is not possible in JPQL. As kostja says: the message says it clear and also according to the JPA specification, Chapter "4.10 Bulk Update and Delete Operations" you may update only state fields and single values object fields.

The syntax of these operations is as follows:

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

WHAT TO DO?

Probably the most clean way to do that is simply to fetch the entities and to add/replace the phone number/s, although you can always do that also with Native Queries, i.e SQL queries as kostja says.




回答2:


The reason for the failure is stated in the error message. You cannot use bulk updates on non-singular attributes of your entity, since they are stored in a different table.

How do you do it instead? You update the collection table.

The default table name for collection tables is <parent_entity>_<field_name>. So the table you are interested in should be named EmployeeImpl_phonenumber. The id column for the EmployeeImpl (the foreign key) should be named EmployeeImpl_id per default.

EDIT What I posted initially was not valid in JPQL. You might want to use a native query instead. It is simple, so it should be portable:

The native query could then look like this:

UPDATE EmplyeeImpl_phonenumber 
SET phonenumber = ? 
WHERE employeeimpl_id = ?


来源:https://stackoverflow.com/questions/20246757/jpql-query-bulk-update-set-on-an-elementcollection-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!