stakowerflol
stakowerflol

Reputation: 1079

Query database with JPA for null values

The value in database can be sometimes NULL and sometimes not. How can I retrieve it? This is my try which makes me suprised:

@Repository
public interface AddressRepo extends JpaRepository<Address, Long>{

    @Query("select count(a) > 0 from Address a where a.street = :street")
    boolean testtest(@Param("street") String street);
}

test OK:

// given
address = new Address("WIELKA WARSZAAAWA", "Bokserska", "xxx", "50-500");
// when
addressRepo.save(address);
// then
assertTrue(addressRepo.testtest("Bokserska")); // OK

test fails:

// given
address = new Address("WIELKA WARSZAAAWA", null, "xxx", "50-500");
// when
addressRepo.save(address);
// then
assertTrue(addressRepo.testtest(null)); // cuz false!

Upvotes: 1

Views: 165

Answers (1)

Dherik
Dherik

Reputation: 19050

The JPQL is not able to translate this statement:

WHERE a.street = null

To this SQL:

WHERE a.street IS null

So, you need to create a new @Query:

select count(a) > 0 from Address a where a.street IS NULL

Mount manually the JPQL string or use Criteria to create a dynamic query are also good options.

Upvotes: 2

Related Questions