Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring JPA Multiple Many-To-One Relationships in One Entity

I'm trying to create an entity, User who has two Addresses, a home address and a work address.

Instead of storing the address info directly in the User class, I want to normalize it and store all addresses in one table and then link them to the user. Like so:

@Entity
public class User {

    @Id
    private Integer id;
    private Address homeAddress;
    private Address workAddress;

    // getters and setters
}

@Entity
public class Address {

    @Id
    @GeneratedValue (strategy = GenerationType.AUTO)
    private Integer id;
    private String streetNumberAndName;
    private String apartmentOrSuiteNumber;
    private String city;
    private String state;
    private String zipcode;

    // getters and setters
}

How do I do this using Spring JPA? I understand this is a ManyToOne relationship but I'm not sure how to map two ManyToOne relationships to one entity. Is this even possible?

Any help much appreciated.

Thanks!

like image 848
alphathesis Avatar asked Oct 24 '25 17:10

alphathesis


1 Answers

That's really simple. Just map your User class like:

@Entity
public class User {

    @Id
    private Integer id;

    @ManyToOne
    @JoinColumn(name = "fk_home_address")
    private Address homeAddress;

    @ManyToOne
    @JoinColumn(name = "fk_work_address")
    private Address workAddress;

    // getters and setters
}

The table structure would be like this:

user(id, fk_home_address, fk_work_address)

Note that this is a unidirectional relationship.

The best place to look for examples if you want to learn more is here. If you're looking for a bidirectional relation, learn here.

like image 102
inafalcao Avatar answered Oct 26 '25 06:10

inafalcao