⚠️ 오류 메시지 (콘솔)

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'postRepository' defined in com.ll.medium.domain.post.post.repository.PostRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Could not create query for public abstract org.springframework.data.domain.Page com.ll.medium.domain.post.post.repository.PostRepository.findByUsername(java.lang.String,org.springframework.data.domain.Pageable); Reason: Failed to create query for method public abstract org.springframework.data.domain.Page com.ll.medium.domain.post.post.repository.PostRepository.findByUsername(java.lang.String,org.springframework.data.domain.Pageable); No property 'username' found for type 'Post'

👉 오류 원인 코드

@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor(access = PROTECTED)
@AllArgsConstructor(access = PROTECTED)
@EqualsAndHashCode
@EntityListeners(AuditingEntityListener.class)
public class Post {
    @Id
    @GeneratedValue(strategy = IDENTITY)
    @EqualsAndHashCode.Include
    private Long id;
    @NotBlank
    private String title;
    @NotBlank
    private String body;
    @ManyToOne
    private Member author;
    @CreatedDate
    private LocalDateTime createDate;
    @LastModifiedDate
    private LocalDateTime modifyDate;
    private boolean isPublished;
}
@Repository
public interface PostRepository extends JpaRepository<Post, Long> {

    List<Post> findTop30ByIsPublishedTrue(Sort sort);

    Page<Post> findByIsPublishedTrue(Pageable pageable);

    // 오류 원인이 된 코드
    Page<Post> findByUsername(String username, Pageable pageable);
}

🔖 오류 발생 이유

PostRepository 에서 Username을 기준으로 조회를 하는 메서드를 만들었기 때문이었습니다.

요청 객체로 부터 username은 DB 조회 없이 바로 가져올 수 있어서 이렇게 하였는데,

Post 테이블에는 username 컬럼은 존재하지 않기 때문에 이 코드로 오류가 발생합니다.

만약 오류가 발생하지 않더라도, 최소 테이블에서 join은 필요하기 때문에 기대했던 성능 개선 효과도 미미했을 것을 알게 되었습니다.

😄 오류 해결

@Repository
public interface PostRepository extends JpaRepository<Post, Long> {

    List<Post> findTop30ByIsPublishedTrue(Sort sort);

    Page<Post> findByIsPublishedTrue(Pageable pageable);

    Page<Post> findByAuthorId(Long authorId, Pageable pageable);
}

Post 테이블에는 Member 엔티티와 관련한 컬럼이 author_id 밖에 없고,
Post 엔티티에서는 Member 필드의 이름을 author라고 하였습니다.

따라서 PostRepository에서 findByAuthor 또는 findByAuthorId 라는 메서드명으로 정의해야 합니다.

(1) Page<Post> findByAuthor(Member author, Pageable pageable);

(2) Page<Post> findByAuthorId(Long authorId, Pageable pageable);

profile
웹 백엔드 프로그래밍 Today I Learned

0개의 댓글

Powered by GraphCDN, the GraphQL CDN