0

I’m using JPA 2.1 and I have an entity object called Encounter that has one-to-one relationships with many other different objects of varying sizes (call them satellite objects). I would like these satellite objects to behave like value objects and be automatically replaced when a new instance of Encounter is saved. I have read many articles that show how to achieve this behavior by making the satellite objects embeddable objects instead of entities in a one-to-one relationship. That would work fine except that for any one “encounter” only a few of the large number satellite objects will be needed. Embedding them in a single table would waste a lot of table space and make the Encounter table more complex than necessary.

So is there a way to make an Entity in a one-to-one relationship behave like a value object without writing a lot of code to check if it exist, then delete it, then persist the new one?

Ross
  • 1,313
  • 4
  • 16
  • 24
Bruce_DDD
  • 95
  • 2
  • 10
  • You can achieve this (or at least a part of this) using Cascade options check this [link](https://vladmihalcea.com/2015/03/05/a-beginners-guide-to-jpa-and-hibernate-cascade-types/) for more details – Ranjeet Jun 09 '17 at 20:09
  • Thanks, I haven’t digested all the information in the link, but I don’t see a clear mapping to my problem. My Encounter Entity is never deleted, but satellite objects are added, modified and sometime replace over time. I get a “Duplicate entry for key” error whenever I have an existing satellite object and a client creates another with “new” so that the ID is not preserved. Is there a cascade type that deletes and replaced a one-to-one mapped entity? – Bruce_DDD Jun 09 '17 at 22:51
  • OneToOne(cascade = ALL, orphanRemoval = true) – JB Nizet Jun 10 '17 at 09:37

0 Answers0