본문 바로가기

전체 글336

트러블 슈팅 : JPA leftjoin N+1 문제 원래 Article 조회 시 모든 join을 fetchjoin으로 하고 있었어서 문제가 없었는데 Article의 Hashtag가 없는 경우 fetchjoin으로 조회할 수 없어서 쿼리를 아래와 같이 변경했다. @Query("select a from Article a " + "join fetch a.category c " + "join fetch a.member m " + "left join a.articleHashtags ah " + "left join ah.hashtag h " + "where a.id =:id") Article findArticleByArticleId(@Param("id") long id); 이랬더니 N+1문제가 발생했다. 해시태그가 만약 2개가 있는경우 조회쿼리1번, ah조회쿼리 1.. 2024. 1. 24.
대댓글 JPA로 구현하기 Comment라는 엔티티를 부모와 자식 상속관계로 구현한다. commentResponseDto.getCommentId() = 1 commentResponseDto.getContent() = 댓글1 commentResponseDto.getParentId() = null child.getContent() = 답글1 commentResponseDto.getCommentId() = 2 commentResponseDto.getContent() = 답글1 commentResponseDto.getParentId() = 1 child.getContent() = 답글1의 답글1 commentResponseDto.getCommentId() = 3 commentResponseDto.getContent() = 답글1의 답글1.. 2024. 1. 23.
spring security에서 로그인 한 사용자의 권한 체크용 간단한 코드 @RestController @RequiredArgsConstructor public class MemberController { @GetMapping("/test/1") // 권환 확인용 public Collection 2024. 1. 18.
좋은 커밋메세지 2024. 1. 11.
SpringDataJPA - EntityGraph, fetch join 간단하게 하기 fetch join을 SpringDataJPA에서는 @EntityGraph 어노테이션을 통해 간단하게 할 수 있다. // 한방쿼리로 들고 오는 fetch join@Query("select m from Member m left join fetch m.team")List findMemberFetchJoin();위의 fetch join 메서드를 EntityGraph를 사용하면 아래와 같이 바꿀 수 있다. EntityGraph를 이용하면 메서드 이름으로 쿼리 생성 + 패치조인처럼 쓸 수 있음@Override@EntityGraph(attributePaths = {"team"})List findAll();jpql 대신 @EntityGraph 어노테이션을 사용한다. attributePaths에 fetch join할 .. 2024. 1. 10.
SpringDataJPA - 벌크성 수정 쿼리 Dirty Checking으로 여러 건 수정시 건마다 쿼리 발생함.쿼리 한 번으로 쫙 다 수정하는 건 JPA에서는 벌크성 수정쿼리라고 함벌크성 수정 쿼리를 이용하면 한 번의 쿼리로 대량의 데이터를 수정할 수 있다. @Modifying 어노테이션 사용Repository 수정 메서드에 @Modifying 을 붙여준다(안붙이면 에러 발생)// 회원의 나이를 변경하는 벌크성 쿼리// age 이상인 경우 1살 추가@Modifying //Modifying이 있어야 JPA의 executeUpdate 호출함@Query("update Member m set m.age = m.age + 1 where m.age >= :age")int bulkAgePlus(@Param("age") int age);  test 코드 예제)@.. 2024. 1. 10.