Skip to content
Advertisement

JPA Embeddables – Multiple per Entity, Single Table for all Entities

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:

JavaScript

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

JavaScript

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

Advertisement

Answer

Thanks to for the assistance, I think a combination of crizzis and latterly Jens’s suggestions led me to this JPA implementation.

JavaScript

with the UUID type def defined as follows in case anyone also needs it

JavaScript

This generates the following DDL in the MySQL database

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement