개발
친구 목록 동기화 시 기존 데이터를 업데이트하지 않고 새로운 데이터로 저장되는 문제
kdozlo
2025. 1. 17. 05:06
문제 상황
- 친구 목록 동기화 과정에서, 이미 존재하는 친구 데이터를 업데이트하고 새 데이터는 추가로 저장해야 한다.
- 하지만 기존 친구 데이터가 업데이트되지 않고, 새로운 데이터로 중복 저장되는 문제가 발생.
원인 분석
- JPA에서 엔티티를 업데이트하려면, 해당 엔티티가 영속성 컨텍스트에서 관리되어야 한다.
- 문제 지점: FriendEntity로 변환하는 과정에서 id가 누락되어, JPA는 이를 새로운 엔티티로 간주하고 저장.
- 결론: id 필드가 없는 경우, JPA는 해당 엔티티를 식별할 수 없어 영속성을 판단하지 못하고, 기존 데이터를 업데이트하지 못함.
문제 코드
- 동기화 로직
// 친구 목록 동기화 로직중 일부
friendRepository
.findByConsumerIdAndToConsumerId(consumerId, toConsumer.getId())
.ifPresentOrElse(friend -> {
friend.toggleFavorite(f.getIsFavorite());
friendRepository.save(friend); // 문제 발생 지점
}, () -> {
friendRepository
.save(Friend.from(consumer, toConsumer, f.getIsFavorite()));
});
- Friend → FriendEntity 변환 로직
// Friend를 FriendEntity로 변환하는 로직
public static FriendEntity from(Friend friend) {
return FriendEntity.builder()
.consumer(friend.getConsumer())
.toConsumer(friend.getToConsumer())
.isFavorite(friend.getIsFavorite())
.build();
}
해결 방법
- Friend에서 FriendEntity로 변환하는 과정에서 id 를 포함하여 JPA가 기존 엔티티를 인식하도록 수정.
public static FriendEntity from(Friend friend) {
return FriendEntity.builder()
.id(friend.getId()) // 해결 방법
.consumer(friend.getConsumer())
.toConsumer(friend.getToConsumer())
.isFavorite(friend.getIsFavorite())
.build();
}