저번 포스팅에서 OneToOne 관계의 주인에서는 지연로딩이 적용되지만 주인이 아니면 지연로딩이 적용되지 않고 EAGER로 데이터가 불러오는 문제에 대해서 다뤄봤다.
그렇다면 해결방법은 뭐가 있을까?
내가 생각한 방법은 OneToOne 연관관계에서 주인이 아닌 쪽에 Long 타입으로 주인의 Seq를 저장하는것이다.
@AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@DynamicInsert
@Getter
@Table(name = "appointment")
@Entity
@Builder
public class Appointment extends BaseEntity {
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Id
private Long appointmentSeq;
@Setter
// join용 seq
private Long review_seq;
.
.
.
이런식으로 컬럼을 작성해놓고 appointment entity가 저장되기 전에 review Seq를 직접 할당해주는 방법을 사용했다.
@Transactional
public void createReview(long appointmentSeq, RequestReviewFormDto requestReviewFormDto) {
Appointment appointment = appointmentRepository.findByIdWhitHospital(appointmentSeq)
.orElseThrow(() -> new IllegalStateException("Can not found Appointment Entity"));
Review review = RequestReviewFormDto.toEntity(requestReviewFormDto, appointment);
Review reviewEntity = reviewRepository.save(review);
// 컬럼에 직접 값을 할당
appointment.setReview_seq(reviewEntity.getReviewSeq()); ;
}
그리고 Appointment를 기준으로 조회를 할때 다음과 같이 쿼리를 작성해서 조회해봤다.
@Repository
public interface AppointmentRepository extends JpaRepository<Appointment, Long> {
@Query("select new com.playdata.eungae.appointment.dto.ResponseAppointmentDto(a.appointmentSeq, r.reviewSeq)"
+ " from Appointment a, Review r"
+ " where a.review_seq = r.reviewSeq"
+ " and a.member.memberSeq = :memberSeq")
// reviewSeq를 where문을 사용해서 조회하는 쿼리
Optional<Page<ResponseAppointmentDto>> findAllWithReview(Pageable pageConfig, @Param("memberSeq") Long memberSeq);
}
성공적으로 한번의 쿼리로 모든 데이터를 조회해올 수 있다.
여기서 Review entity와 Appointment Entity의 데이터를 모두 받아오기 위해 Dto를 정의해서 각각 시퀀스값을 조회해왔다.
'코딩딩 > Error' 카테고리의 다른 글
Spring Data JPA 사용시 Repository BeanCreationException (0) | 2024.01.09 |
---|---|
파이썬 셀레니움 웹 스크레핑 시 hidden에 숨겨져있는 src 경로 가져오기 (3) | 2024.01.08 |
OneToOne 관계에서 N+1 문제가 발생하는 이유 (2) | 2024.01.04 |
Builder 패턴 사용시 ArrayList가 초기화 되지 않는 문제 (1) | 2024.01.03 |
Null값이 들어올 수 없는 @PathVariable에도 Wrapper class를 사용해야 할까? (1) | 2023.12.28 |