Back End/Spring Data JPA
save() 메서드 호출 시, select 쿼리가 하나 더 나가요 ㅠㅠ...
DevPing9_
2022. 2. 17. 12:25
# 발생 기원
1. 엔티티의 PK 를 직접할당하고 save() 호출 시 목격 됨
PK 생성을 DB에 위임하지 않았을 시 발생하는 문제와 해결 (feat.복합키) · Issue #5 · Sun26-Avrin/study-sp
PK 생성을 DB에 위임하지 않았을 시 목격되는 현상 엔티티를 생성하고 insert를 위한 로직에서 select쿼리가 하나 더 호출 되는 현상 이러한 현상의 이유는? 프록시객체는 PK를 기반으로 움직이며, PK
github.com
# 이유
em.persist() 가 아닌 em.merge()가 호출되기 때문
save() 메서드의 내부 코드를 보면 entityInformation.isNew(이하 isNew) 로 persist와 merge로 분기함.
엔티티의 PK가 null 이거나 초기화 값인 경우(원시타입, ex[ 0, 0L] ) isNew는 True, 그 외의 경우는 False 로 처리된다.
# save() 메서드 내부코드

# 해결방법
Persistable 인터페이스를 오버라이딩 한다.
# 예시코드
@Entity
public class User implements Persistable<Long>{
@Id
long id;
@Override
public Long getId() {
// TODO Auto-generated method stub
return this.id;
}
@Transient
boolean isNew=true;
@Override
public boolean isNew() {
// TODO Auto-generated method stub
return this.isNew;
}
@PostPersist
@PostLoad
public void modifyIsNew(){
this.isNew=false;
}
}
728x90