0

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?

erotsppa
  • 14,248
  • 33
  • 123
  • 181
  • can you post your relevant code so that it helps us to understand where can be the problem? – user404 Apr 17 '20 at 15:54
  • seems like you're having a Collection of Pet in User entity? – Mr.J4mes Apr 17 '20 at 16:13
  • 1
    You could put a unique constraint at SQL level. Also, here is a good read, especially if you want your relationship to be lazy: https://vladmihalcea.com/the-best-way-to-map-a-onetoone-relationship-with-jpa-and-hibernate/. – sp00m Apr 17 '20 at 16:45
  • I guess the unique constraint could work, how do I specify that in code? – erotsppa Apr 17 '20 at 17:37
  • See https://stackoverflow.com/questions/3126769/uniqueconstraint-annotation-in-java – Rodrigo Apr 18 '20 at 02:19

0 Answers0