programing

열이 null인 스프링 데이터 쿼리

sourcejob 2023. 7. 28. 21:59
반응형

열이 null인 스프링 데이터 쿼리

엔티티가 있다고 가정합니다(간단하게 설명하기 위해 게터/세터 및 다양한 세부사항 생략).

@Entity
class Customer{
    ...
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "customer")
    Collection<Coupon> coupons;
}

@Entity
class Coupon{
    ...
    @Temporal(value = TemporalType.TIMESTAMP)
    private Date usedOn;

    @ManyToOne(fetch = FetchType.LAZY)
    @NotNull
    Customer customer;
}

Null이 On으로 사용된 특정 고객에 대한 모든 쿠폰을 검색합니다.I, 문서에 설명된 대로 쿠폰 저장소에서 메서드를 정의하지 못했습니다.

@Repository
public interface CouponRepository extends CrudRepository<Coupon, Long> {
     Collection<Coupon> findByCustomerAndUsedOnIsNull(Customer);
}

하지만 이것은 컴파일러 오류로 이어집니다.Syntax error, insert "... VariableDeclaratorId" to complete FormalParameterList.

내 잘못, 올바른 정의는

@Repository
public interface CouponRepository extends CrudRepository<Coupon, Long> {
     Collection<Coupon> findByCustomerAndUsedOnIsNull(Customer customer);
}

단순히 매개 변수 이름을 놓쳤습니다 :-(

IsNull을 사용하여 JPA 쿼리의 null 열을 확인할 수 있습니다.

예를 들어, 모든 열 A에 대해 쿼리와 같은 쿼리를 쓸 수 있습니다.

findByColumnAIsNull

이 경우 다음과 같은 쿼리를 작성할 수 있습니다.

@Repository
public interface CouponRepository extends CrudRepository<Coupon, Long> {
 Collection<Coupon> findByCustomerAndUsedOnIsNull(Customer customer);
 List<Coupon> findByUsedOnIsNull();
}

또한 이 쿼리가 어떻게 될 것인지 확인할 수 있습니다. 이 스프링 데이터 JPA 쿼리 생성을 참조하면 다양한 유형의 JPA 쿼리 변형을 이해하고 만드는 데 도움이 될 것입니다.

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/ #jpa.jpa-discovery.discreation

방법을 다음으로 변경해 보십시오(가정).Customer.id길이가 깁니다):

Collection<Coupon> findByCustomer_IdAndUsedOnIsNull(Long customerId);

다음과 같이 사용합니다.

repo.findByCustomer_IdAndUsedOnIsNull(customer.getId());

언급URL : https://stackoverflow.com/questions/29448282/spring-data-query-where-column-is-null

반응형