JPA @OneToOne 매핑이 안된다고? Unique

JPA를 사용하면서 @OneToOne 어노테이션을 많이 보고 사용했을 것이다. 이 글에서는 OneToOne 어노테이션을 사용했는데도, 데이터가 한개가 아닌 2개가 들어가서 @OneToMany로 들어가는 일이 있거나, 그런 궁금증을 가지신 분들이 보면 도움이 될 수 있다고 생각한다.

Situation

  1. 두개의 1대1 양방향 관계의 엔티티가 있습니다. (Son, Parent)
@Entity

@Table

public class Son {

   @Id

   @Column

   private String name;

   @Column

   Integer age;

   @JoinColumn

   @OneToOne

   private  Parent parent;

}
  1. 각자의 엔티티를 사용해서, Son 객체 2개를 생성해서 똑같은 부모 Foreign키를 사용해보겠습니다.
@Entity

@Table

public class Parent {

   @Id

   @Column

   private String name;

   @Column

   private Integer age;

   @OneToOne(mappedBy = "parent")

   @JoinColumn

   private Son son;

}
  1. 구동결과

public static void main(String[] args) {

EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");

EntityManager em = emf.createEntityManager();

EntityTransaction tx = em.getTransaction();

tx.begin();

Parent parent = new Parent();

parent.setName("엄마");

Son son1 = new Son();

Son son2 = new Son();

son1.setName("아들1");

son1.setAge(11);

son1.setParent(parent);

parent.setSon(son1);

son2.setName("아들2");

son2.setAge(10);

son2.setParent(parent);

em.persist(parent);

em.persist(son1);

em.persist(son2);

tx.commit();

em.close();

emf.close();


}

}

- 이상하게 너무 잘돌아간다. (아들1과 아들2는 알고보니 형제였던거임)

![<https://blog.kakaocdn.net/dn/d3WCUB/btqMvLoO0pH/YwUFuYeYsxtPDiUr5mYaIk/img.png>](<https://blog.kakaocdn.net/dn/d3WCUB/btqMvLoO0pH/YwUFuYeYsxtPDiUr5mYaIk/img.png>)

- Hibernate 를 보면 OneToOne 을 비웃기라도 한듯이 너무 잘들어 간다.
    
    ![<https://blog.kakaocdn.net/dn/xQMVx/btqMveSjxnx/MuMLQoTTWNLlMmNvubtK2k/img.png>](<https://blog.kakaocdn.net/dn/xQMVx/btqMveSjxnx/MuMLQoTTWNLlMmNvubtK2k/img.png>)
    

사실 정상적인 구동 결과이다. DB자체에다가, 물리적으로 제약을 걸어준 것도 아니고, 자바입장에서도 객체 레퍼런스값을 집어넣는데 문제가 생길 이유도 명분도 없다.