Nadeem Haider
Nadeem Haider

Reputation: 170

Hibernate map field of an Entity as a foreign key to multiple Entities

I want to save address of User and Employee entities in the Address entity. How do I design my Address entitiy so that I am able to save address of a User as well as an Employee.

Upvotes: 0

Views: 446

Answers (2)

Azad
Azad

Reputation: 171

  1. Create an abstract base class Person with Address Entity as a member.
  2. Extend the Person class in User and Employee sub-classes.

    @MappedSuperclass
    abstract class Person {
        @ManyToOne @JoinColumn(name="ADDRESS")
        protected Address address;
    }
    
    @Entity
    class Employee extends Person {}
    
    @Entity
    class User extends Person {}

Upvotes: 3

Alejandro Casagrande
Alejandro Casagrande

Reputation: 56

You have two options, one is to make the Address Entity embeddable,

@Embeddable
public class Address {
   ....
}

@Entity
public class User {
     .....
    @Embedded
    private Address address;

}

@Entity
public class Employee {
     .....
    @Embedded
    private Address address;

}

This will copy the columns in the table Employee and in the table User.

Another approach is to use the address as a table if you want to share addresses:

@Entity
public class Address {
   ....
}

@Entity
public class User {
     .....
    @ManyToOne
    private Address address;

}

@Entity
public class Employee {
     .....
    @ManyToOne
    private Address address;

}

Upvotes: 1

Related Questions