@Entity
@Getter
@Setter
public class Locker {
@Id
@GeneratedValue
@Column(name="locker_id")
private long id;
private String name;
@OneToOne(mappedBy="locker")
private Member member;
public Locker(String name) {
this.name= name;
}
public void setMember(Member member)
{
if(member.getLocker()!=this)
member.setLocker(this);
}
}
@Entity
@NoArgsConstructor
@Getter
@Setter
public class Member {
@Id
@GeneratedValue
private long id;
private String name;
@ManyToOne
@JoinColumn(name="TEAM_ID")
private Team team;
@OneToOne
@JoinColumn(name="locker_id")
private Locker locker;
//무한 루프를 막는 로직
public void setTeam(Team team)
{
//양방향이라 맵핑 되는 부분을 서로 셋팅을 해줘야 하는데 .
//일단 Member 의 team은 셋팅
this.team = team;
//Team에도 Member를 셋팅하기 전에 이미 member가 포함되어있지 않아야만 셋팅 해줄수있다 Team클래스도 마찬가지
if(!team.getMembers().contains(this))
{
team.getMembers().add(this);
}
}
public void setLocker(Locker locker)
{
this.locker= locker;
if(locker.getMember() == null)
{
locker.setMember(this);
}
}
public Member(String name) {
this.name= name;
}
}
실행 로직
@Component
@Transactional
public class JpaRunner implements ApplicationRunner{
@PersistenceContext
EntityManager entityManager;
public void oneToOne()
{
Member member1 = new Member("member1");
Member member2 = new Member("member2");
Member member3 = new Member("member3");
entityManager.persist(member1);
entityManager.persist(member2);
entityManager.persist(member3);
Locker locker1 = new Locker("locker4");
Locker locker2 = new Locker("locker5");
Locker locker3 = new Locker("locker6");
entityManager.persist(locker1);
entityManager.persist(locker2);
entityManager.persist(locker3);
member1.setLocker(locker1);
member2.setLocker(locker2);
member3.setLocker(locker3);
}
public void ManyToOne()
{
}
@Override
public void run(ApplicationArguments args) throws Exception {
oneToOne();
}
}