I have a entity relationship setup as @OneToOne. For example (User <--> Pet)
@Entity
public class Pet {
@OneToOne
@JoinColumn(name = "user_id", nullable = true)
User user;
}
@Entity
public class User {
@OneToOne(mappedBy = "user")
Pet pet;
}
To my surprise, Spring will allow you to assign multiple entities into the relationship (Multiple Pets associated with User) when you save via the repositories.
//for example:
pet.user = user1;
pet2.user = user1;
petRepository.save(pet);
petRepository.save(pet2); //allowed
But then after the save, the database will now be corrupted. By calling petRepository.findAll or findById or anything really...will now yield this error
nested exception is org.hibernate.HibernateException: More than one row with the given identifier was found: 1245, for class: package.models.Pet
So what is the proper way to ensure OneToOne relationship so as to not corrupt the db?