java - JPA @OneToOne with same type -


how annotate code have person 2 addresses :

@entity public person {      // ... other attributes person      @onetoone     public address homeaddress;      @onetoone     public address workaddress; }  @entity public address {      // ... other attributes address      @onetoone     public person person; } 

can use onetoone ? should have use options on annotations ?

unfortunately not possible achieve @onetoone. reason:

the persistence provider have 1 person id 2 entries address table. not sufficient decide relation given address belongs to.

the simplest solution add type field (an enum) address entity , map addresses @onetomany/@manytoone.

in order home address, need iterate on addresses , check type.

alternatively, create types homeaddress , workaddress derive address. keep @onetoone relations, end 2 additional types.

imo cleaner entity relation mapping not sufficient reason doing this, inviting issues. example homeaddress can never workaddress.

edit: if both address ids stored in person table, should able use the@onetoone relation. ensure deletion of attached address entities , deletion of orphaned address entities, can use cascading , orphan removal:

@onetoone(cascade=cascadetype.all, orphanremoval=true) 

although might makes sure there no orphaned address records in db, not entirely true. orphan removal works when remove referenced entity inside transaction while entities attached. furthermore not work bulk updates. delete person ... query happily delete persons , not touch connected addresses.


Comments

Popular posts from this blog

php - Why I am getting the Error "Commands out of sync; you can't run this command now" -

linux - Does gcc have any options to add version info in ELF binary file? -

java - Are there any classes that implement javax.persistence.Parameter<T>? -