I'd like to update a collection field List<Bar> bars
in JPA entity Foo
, but without changing the original one - just set the updatedBars
to bars
field before save.
But my code isn't working, probably because the updatedBars
are not persistent despite the fact that some Bar
objects are from original collection.
Any suggestions, please.
P.S. This way of updating collection seems easier to me, because I can just populate an updatedBars
in stream copying and updating, creating, and just ignoring values from original collection instead of performing separate operations like remove, update, add on the original collection.
Here is my code example:
@Getter
@Setter
@Entity
@Table(name = "foo")
public class Foo {
@Id
@Column(name = "id")
private Long id;
@JoinColumn(name = "foo_id")
@OneToMany(fetch = FetchType.LAZY, orphanRemoval = true, cascade = CascadeType.ALL)
private List<Bar> bars;
}
@Getter
@Setter
@Entity
@Table(name = "bar")
public class Bar {
@Id
@Column(name = "id")
private Long id;
@Column(name = "foo_id")
private Long fooId;
@Column(name = "value")
private Long value;
}
@Transactional
public void refresh(Long fooId){
Foo foo = fooRepository.find(fooId);
List<Bar> updatedBars = getUpdatedBars(foo.getBars());
foo.setBars(updatedBars);
}
private List<Bar> getUpdatedBars(List<Bar> originalBars) {
//do any staff to return new list of Bars, not changing the original one
//some items are removed, some updated (same entity from original list, with changed value field), some added (entities without ids)
}
UPDATE: Updating the content of original collection also did't work.
@Transactional
public void refresh(Long fooId){
Foo foo = fooRepository.find(fooId);
List<Bar> originalBars = foo.getBars();
List<Bar> updatedBars = getUpdatedBars(originalBars);
originalBars.clear();
originalBars.addAll(updatedBars);
}