gpt4 book ai didi

java - Hibernate: OneToOne: 同一类型的两个字段

转载 作者:行者123 更新时间:2023-12-05 08:49:31 28 4
gpt4 key购买 nike

假设我有一个 Person 实体和一个 Animal 实体;一个可以有两个最喜欢的动物,一个动物只能有一个 喜欢他们的人(一个人喜欢一种动物使得其他人不再可能喜欢/看到该动物)。它是一个@OneToOne 映射:对于Person 中的两个Animal 字段和Person 中的两个字段动物。但是,在 Animal 中,firstPerson 应该 ==secondPerson。有没有一种方法可以只对 Animal 类中的一个 Person 字段执行以下操作?

Person.java:

@Entity
@SequenceGenerator(name="PERSON_SEQ", sequenceName="person_sequence")
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="PERSON_SEQ")
private Long id;

@Column
private String name;

public Person() {}

@OneToOne
@JoinColumn(name = "firstAnimal")
private Animal firstAnimal;
@OneToOne
@JoinColumn(name = "secondAnimal")
private Animal secondAnimal;

//getters and setters

Animal.java:

@Entity
@SequenceGenerator(name="PRIVATE_SEQ", sequenceName="private_sequence")
public class Animal {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="PRIVATE_SEQ")
private Long id;

@Column
private String name;

@OneToOne(mappedBy = "firstAnimal")
private Person firstPerson;

@OneToOne(mappedBy = "secondAnimal")
private Person secondPerson;
...

最佳答案

在这种情况下,您可能希望使用 @OneToMany/@ManyToOne 来获得永久解决方案。

Person.java:

@Entity
@Table(name = "...")
public class Person {

@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "org.hibernate.id.UUIDGenerator")
@Column(name="person_id")
private Long id;

@Column(name="...")
private String name;

@OneToMany(mappedBy = "owner", cascade = CascadeType.?)
private List<Animal> animals;

}

Animal.java:

@Entity
@Table(name = "...")
public class Animal {
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "org.hibernate.id.UUIDGenerator")
@Column(name = "...")
private Long id;

@Column(name = "...")
private String name;

@ManyToOne
@JoinColumn(name="columnName", referencedColumnName="person_id")
private Person owner;

}

对于进一步的限制,例如一个人最多只能拥有 2 只最喜欢的动物,或者一只动物只能由 1 个人拥有,您可以使用代码逻辑检查它们。

关于java - Hibernate: OneToOne: 同一类型的两个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63912257/

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