alphathesis
alphathesis

Reputation: 239

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!

Upvotes: 4

Views: 13753

Answers (2)

Huy Nguyen
Huy Nguyen

Reputation: 2061

private Integer id;
private Address homeAddress;
private Address workAddress;

with first situation, your structure table will be

user(id,home_address_id,work_address_id)

You might consider about second structure

private Integer id;
private List<Address> userddress;//using one to many

your table structure will be

address(id,user_id)

It depend how do you want to organize the structure.

Upvotes: 0

inafalcao
inafalcao

Reputation: 1452

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.

Upvotes: 6

Related Questions