본문 바로가기
JPA

[JPA] @OrderBy

by kdohyeon (김대니) 2023. 2. 3.
반응형

두 개의 Entity 가 @OneToMany, @ManyToOne 어노테이션을 활용하여 1:N 관계로 맵핑이 되어 있는 경우에 JPA 로 부모 Entity 를 조회하게 되면 자식 Entity 들도 알아서 조회가 된다. 매번 부모 Entity 기준으로만 조회를 했었어서 함께 조회되는 자식 Entity 에 대해서는 크게 신경을 쓰지 않았었다. 그런데 조회한 자식 Entity 를 최신순으로 정렬해야 하는 필요성이 생겨서 고민을 하다가 @OrderBy 라는 어노테이션으로 해결한 케이스를 적어본다. 생각보다 간단했다.

문제 상황

1:N 관계의 두 개의 Entity 가 존재한다. 부모 EntityProduct 이고, 자식 EntityProductHistory 이다.

@Entity
public class Product {
    @Id
    private Long productId;

    @OneToMany(
        mappedBy = "product"
    )
    private List<ProductHistory> productHistories = new ArrayList<>();
}

@Entity
public class ProductHistory {
    @Id
    private Long productHistoryId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "product_id")
    private Product product;
}

Product 을 조회하면 맵핑되어 있는 ProductHistory 를 함께 조회할 수 있는데 ProductHistory 의 정렬 순서는 id ASC 순이다. 만약 다른 필드 기준으로 정렬을 하고 싶다면 @OrderBy 어노테이션을 활용하면 된다.

@OrderBy 를 이용해 해결하기

부모 Entity 에서 @OrderBy 어노테이션을 부여하면서 대상 테이블의 필드와 정렬/역정렬을 지정해주면 된다. 기본값은 PK ASC 이다.

@Entity
public class Product {
    @Id
    private Long productId;

    @OneToMany(
        mappedBy = "product"
    )
    @OrderBy("product_history_id DESC") // 추가
    private List<ProductHistory> productHistories = new ArrayList<>();
}
반응형

'JPA' 카테고리의 다른 글

[JPA] Spring 에서 JPA 사용하기  (0) 2023.02.11
[JPA] @ManyToOne, @OneToMany 를 활용하기  (0) 2023.02.10
[JPA] @EnableJpaAuditing 활용하기  (2) 2023.02.03

댓글