관계에는 항상 두 엔티티가 존재 합니다.
@Entity
public class Study {
@Id @GeneratedValue
private Long id;
private String name;
@ManyToOne
private Account owner;
}
@Override
public void run(ApplicationArguments args) throws Exception {
Account account = new Account();
account.setUsername("cmlee2");
account.setPassword("pass2");
Study study = new Study();
study.setName("spring jpa");
study.setOwner(account);
Session session = entityManager.unwrap(Session.class);
session.save(account);
session.save(study);
}
반대로 설정 해보자
@Entity
public class Account {
@Id @GeneratedValue
private Long id;
@Column(nullable = false, unique = true)
private String username;
private String password;
@OneToMany
private Set<Study> studies = new HashSet<>();
}
@Override
public void run(ApplicationArguments args) throws Exception {
Account account = new Account();
account.setUsername("cmlee2");
account.setPassword("pass2");
Study study = new Study();
study.setName("spring jpa");
account.getStudies().add(study);
Session session = entityManager.unwrap(Session.class);
session.save(account);
session.save(study);
// entityManager.persist(account);
}
단 방향에서의 관계의 주인은 명확합니다.