Proper way to update a Set element in a JPA @OneToMany relationship?

Viewed 3026

Lets assume we have a bi-directional One-to-Many relationship between Parent and Child.

I like the idea of model that relationship with a Set, because of it intrinsic nature of disallowing duplicates.

Question:
1) What would be the proper JPA way to update a child in such a situation?

  • Query the Parent and pass an updated Child into it?
  • Query the Child directly and just call its setters?

2) Has either way some performance advantages or disadvantages?

@Entity
public class Parent extends AbstractPersistable<Long> {

    @OneToMany(cascade = CascadeType.ALL, ... )
    private Set<Child> children = new HashSet();

    public void addChild( Child child ) { ... }
    public void removeChild( Child child ) { ... }

    // non-anemic domain model ?
    public void updateChild( Child child ) {
        // how to update the element in the Set?
    }
}

UPDATE:
How to properly write the update method? Since Sets in Java do not have a get method?

1 Answers
Related