Suppose I have a Person
entity and an Animal
entity; A Person
can have two favourite animals and an Animal
can only have one Person
that likes them (one person liking an animal makes it no longer possible for other people to like/see that animal). It is a @OneToOne
mapping: for the two Animal
fields in Person
and for the two Person
fields in Animal
. However, in Animal
firstPerson
should ==
to secondPerson
. Is there a way to do the following with only one Person
field in the Animal
class?
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;
...