2

我有班级用户和班级地址。地址仅包含 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
}

当一个实体(User有两个(或多个)字段具有自己的某个自定义类Address)的类型时,选择哪种类型的 JPA 关系以及如何通过注释来实现它

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

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

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

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

我将不胜感激任何建议!

4

1 回答 1

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;
    }
}

并且班级地址保持不变。

于 2012-11-11T16:54:27.613 回答