I'm exploring options for being able to store specific addresses (home, work etc.) for multiple entities, and having a single table that holds all addresses, probably with some kind of discriminator per record. The primary keys for all tables are UUIDs.
I'm using Spring Boot 2.3.6 and JPA/Hibernate.
Ideally I'd like to use named properties per entity, rather than holding a collection of entities as it will make DTO mapping and updates easier.
It's not an issue for me if there are entries in the shared Address table with all NULL values for each entity & property pair if no data is entered.
In pseudo code, I'd like to be able to define the entities as:
@Entity
class Person {
private Address homeAddress;
private Address workAddress;
}
@Entity
class Incident {
private Address incidentLocation;
}
@Entity
class Address {
private String street;
private String zip;
}
I've researched using JPA options such as @Embeddable
's and the options I have seen are to either a) have a single embeddable per entity (I want multiples) b) use @CollectionTable
(I want specific named properties) or c) use @AttributeOverride
which will mean repeated & renamed columns in the table for each property.
I've also looked at @JoinTable
and @OneToMany
but again this is geared towards using collections.
I get the feeling that @Embeddable
is what I need, but need to be able to specify a discriminator for each property that uses this type (homeAddress, workAddress, incidentLocation) so that the data in the Address table follows the format
id type street zip
=========================================
UUID-1 HOME 1 Main St 30002
UUID-1 WORK 10 North St 30005
UUID-2 INCIDENT 5 West Ave 30008
As a bonus, I'd also like (if I could) to be able to create a JpaRepository<Address>
that allows me to query/update the addresses independently of the parent entity.
With all the options available I wondered if anyone knew if there was a way to achieve what I want, or will I have to go down the collection route in order to achieve this? Thanks