Giovanni Lovato
Giovanni Lovato

Reputation: 2273

JPA add element to collection using CriteriaUpdate

I'm on Hibernate (5.1) and I need to add an element to a collection field on all entities matching a criteria, without the need to fetch them all.

@Entity
public class Order {

    @Id
    public Long id;

    public Date placedOn;

    @ManyToMany
    public List<Item> items;

}

I need to add the same instance of a new Item to all Orders placed after a certain date. I need to use the Criteria API, not JPQL.

Is that possible? I can't find documentation on this.

P.S. The order/items case is just an example, I'm looking for a generalized method and I'll also need to adapt it to remove items from collections.

Upvotes: 0

Views: 986

Answers (1)

Simon Martinelli
Simon Martinelli

Reputation: 36143

You cannot do that using CriteriaUpdate because it's not an update but many inserts because you have a ManyToMany relationship that relays on a relationship table in the database.

So you must query all Orders and then add the Item that will then generate the insert statements.

Upvotes: 1

Related Questions