Polymorphic association in JPA

Viewed 56

I like to have a single table ADDRESS in the Database and multiple unrelated entities for example User, Office will have one to many relations with the Address entity. In a nutshell my Entities would looke like

@Entity 
public class Address {

@Id 
private long id;

@Column 
private String entityType; // served as discriminator e-g User,Office ...

@Column 
private long entityId; // served as foreign key

... other address columns    
}

User Class

public class User {

@Id 
private long id;

@OneToMany
private List<Adress> addresses;t

}

Office class

@Entity
public class Office {
   @Id 
    private long id;
    
    @OneToMany
    private List<Adress> addresses;
    
}

I tried @Any of Hibernate but that's not helping with One-to-Many relations. It has either Many-to-One and Many-to-Many relationships. What is the best way to achieve this in JPA.

0 Answers
Related