Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring data query where column is null

Suppose I have entities (getters/setters and various details omitted for brevity):

@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; } 

I wish retrieve all Coupons for a given Customer having null usedOn. I,'ve unsuccessfully defined a method in the CouponRepository as described in docs

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

but this leads on a compiler error Syntax error, insert "... VariableDeclaratorId" to complete FormalParameterList.

like image 583
lrkwz Avatar asked Apr 04 '15 15:04

lrkwz


People also ask

How does JPA handle null values?

The JPA specification defines that during ordering, NULL values shall be handled in the same way as determined by the SQL standard. The standard specifies that all null values shall be returned before or after all non-null values. It's up to the database to pick one of the two options.

Is Empty JPA query?

The IS EMPTY operator is the logical equivalent of IS NULL, but for collections. Queries can use IS EMPTY operator or IS NOT EMPTY to check whether a collection association path resolves to an empty collection or has at least one value. We can use the EMPTY to check if a property is empty.

What is difference between JpaRepository and CrudRepository?

CrudRepository provides CRUD functions. PagingAndSortingRepository provides methods to do pagination and sort records. JpaRepository provides JPA related methods such as flushing the persistence context and delete records in a batch.

Is null or is not null?

The IS NULL condition is satisfied if the column contains a null value or if the expression cannot be evaluated because it contains one or more null values. If you use the IS NOT NULL operator, the condition is satisfied when the operand is column value that is not null, or an expression that does not evaluate to null.


1 Answers

My fault, the correct definition is

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

I simply missed the parameter name :-(

like image 108
lrkwz Avatar answered Oct 13 '22 19:10

lrkwz