1

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!
5
  • You need a query with where a.street is null. Commented Dec 8, 2018 at 17:38
  • but then normal Queries when street is not null won't work! Commented Dec 8, 2018 at 17:53
  • 1
    You're allowed to use more than a single query. Use the right one depending on what you want to query. Commented Dec 8, 2018 at 17:58
  • this will be very uncomfortable to have 12 ifs for this example... if(street ==null) {addressRepo.testtest2} ... if(city == null) {..} if(street == null && city == null) {...} etc. Commented Dec 8, 2018 at 18:35
  • 1
    That's why the criteria API, or QueryDSL, exist: to dynamically create queries. Commented Dec 8, 2018 at 18:39

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.