在这种情况下如何定义JPA关系的类型?

时间:2012-11-11 16:15:47

标签: hibernate jpa orm jpa-2.0 relationship

我有班级用户和班级地址。 地址仅包含4个属性:

publiс class Address {

    private Long id;
    private String country;
    private String city;
    private String street;

    // getters and setters
}

用户的结构:

public class User {
    private Long id;
    private String name;
    private Address homeAddress;
    private Address businessAddress;

    // other fields and methods
}

当一个实体用户有两个时,选择哪种类型的JPA关系以及如何通过注释进行注释(或更多)具有某种自定义类型的字段地址

如果用户只有一个地址,那将是一对多的关系。但是这个案子怎么样?如何在我的系统中正确定义这些对象?

我尝试在Address类中创建另一个字段users

@OneToMany(mappedBy = "?")
private List<User> users;

但这不是我问题的解决方案,因为User类中有两个Address类型字段。并且不清楚是否有必要在mappedBy注释中定义...

我将不胜感激任何建议!

1 个答案:

答案 0 :(得分:0)

    public class User {
    private Long id;
    private String name;
    private Address homeAddress;
    private Address businessAddress;

    // other fields and methods

    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "HOME_ADDRESS_ID")
    public Address getHomeAddress() {
        return homeAddress;
    }

    public void sethOMEAddress(Address homeAddress) {
        this.homeAddress= homeAddress;
    }

    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "BUSINESS_ADDRESS_ID")
    public Address getBusinessAddress() {
        return businessAddress;
    }

    public void setBusinessAddress(Address businessAddress) {
        this.businessAddress= businessAddress;
    }
}

并且类地址保持不变。