Search code examples
jpajpqlbulkupdate

JPQL Query Bulk UPDATE SET on an ElementCollection field


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.


Solution

  • 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.