JpaRepository를 이용해 외래키 값으로 조회하는 방법에 대해서 알아보자!
Board.class
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Entity
public class Board extends BaseTimeEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(length = 40, nullable = false)
private String title;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
private User user;
}
User.class
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Entity
public class User extends BaseTimeEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String email;
@Column(nullable = false)
private String password;
}
findBy + FK 형태로 조회하는 경우 다음과 같은 규칙을 적용하면 된다.
findBy + {FK를 관리하는 entity 필드명에서 첫글자를 대문자} + _ +
{FK entity의 식별자 필드명에서 첫글자를 대문자}
BoardRepository.interface
@Repository
public interface BoardRepository extends JpaRepository<Board, Long> {
List<Board> findByUser_Id(Long user_id);
}
참고 블로그 :
JPA - find by 외래키(FK) 조회 방법
안녕하세요 오늘은 JPA 사용시 @Entity를 외래키의 값을 통해 조회하는 방법을 알아 보려고 합니다. 대부분 간단한CRUD의 경우 JpaRepository를 통해 쉽고 빠르게 처리합니다. 하지만 Entity의 컬럼값으로
pooney.tistory.com