0

FooObject has an entity with a few lists of bar objects managed by entities. Whenever I edit FooObject and call update on it, all of those lists are added to, not replaced.

   @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, 
              mappedBy = "barEntity", targetEntity = BarTypeAEntity.class)
   private List<BarTypeAEntity> barTypeAs;

I can first remove all the lists before calling update but in auditing these tables it appears as a delete then an new creation, rather than just one update.

How can I just simply overwrite rather than append these lists

OPK
  • 4,120
  • 6
  • 36
  • 66
Andrew
  • 735
  • 1
  • 6
  • 9

1 Answers1

0

Use orphanRemoval = true. This tells Hibernate that if you remove BarTypeAEntity object from the collection of barTypeAsand then save FooObject, the removed BarTypeAEntityshould be deleted from the underlying DB.

@OneToMany( cascade = CascadeType.ALL, fetch = FetchType.LAZY, 
              mappedBy = "barEntity", targetEntity = BarTypeAEntity.class,
              orphanRemoval = true )

private List<BarTypeAEntity> barTypeAs;

And do something like this for update

foo.getBarTypeAs().clear();
foo.getBarTypeAs().add(new BarTypeAEntity());
v.ladynev
  • 19,275
  • 8
  • 46
  • 67
  • 1
    I also found the same solution here, with slightly more details. http://stackoverflow.com/questions/14686595/hibernate-onetomany-remove-child-from-list-when-updating-parent The only problem with this solution is auditing - my bar entities are shown as deleted then created again. – Andrew Dec 17 '15 at 13:07
  • @Andrew Sorry, can't got you with "auditing" – v.ladynev Dec 17 '15 at 14:13
  • y orpanRemoval = true? can you explain? – tharindu_DG Dec 19 '15 at 10:57