JPQL VO 속성 조건으로 쿼리 작성하는 법

장서연·2022년 12월 9일
0
public interface ProductRepository extends JpaRepository<Product, Long> {
    Optional<List<Product>> findByNameContaining(String name);
    List<Product> findByNameLikeOrDetailLike(String name, String detail);

    List<Product> findByPriceLessThanEqualOrderByPriceDesc(Money price);

    @Query("select p from Product p where p.detail like %:detali% order by p.price desc") // p.price 는 Money 타입의 객체
    List<Product> findByDetail(String detail);
}

위 코드는 아래와 같은 에러가 난다.

"정렬 가능한 속성이 없다"

price 를 int 나 Long 등의 정렬 가능한 속성이 아닌 Money 라는 밸류오브젝트(vo) 클래스를 직접 만들어 정의했기에 위와 같은 문제가 발생했다. 정렬가능한 속성이 없다길래, 정렬가능하게 Money 클래스에 Comparable 을 구현하여 해결해주었다.

@Getter
@EqualsAndHashCode(of = {"value"})
public class Money implements Comparable<Money>{
    private Integer value;
    public Money(int value) {
        this.value = value;
    }

    public Money() {

    }

    public Money add(Money money) {
        return new Money(this.value + money.value);
    }
    public Money multiply(int multiplier) {
        return new Money(value * multiplier);
    }

    @Override
    public int compareTo(Money money) {
        return this.getValue().compareTo(money.value);
    }
}

오류가 사라진 것을 볼 수 있다

0개의 댓글