gpt4 book ai didi

java - @ManyToOne 和@OneToOne 在同一实体上

转载 作者:行者123 更新时间:2023-11-30 07:39:48 25 4
gpt4 key购买 nike

假设我们有这两个实体:

@Entity
class Address{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long bookId;

@ManyToOne
@OneToOne
private User user;

...
}

@Entity
class User{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long userId;

@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private List<Address> addresses;

@OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
private Address principalAddress;

...
}

如您所见,我在 Address 类中的用户实体顶部有两个注释(@ManyToOne 和@OneToOne)。关键是,我知道这是错误的,但我不知道如何正确映射它。设计有问题吗?逻辑是用户有一个地址列表和一个且唯一的主要地址。我怎样才能正确映射它?有什么想法吗?

最佳答案

在这种情况下,您可以做的是标记“isPrincipalAddress”。

@Entity
class Address{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long bookId;

private Boolean isPrincipalAddress;

@ManyToOne
private User user;

...
}

@Entity
class User{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long userId;

@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private List<Address> addresses;

...
}

关于java - @ManyToOne 和@OneToOne 在同一实体上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59048617/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com