JPA Query dla NULLowych wartości

0

taka sytuacja:

@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 zły:

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

Jak przeszukiwać nule w JPA Query?

0

Ta metoda zwraca primityw boolean, więc nigdy nie zwróci nulla. Czemu po prostu nie zrobisz

assertTrue(!addressRepo.testtest(null));

?

0

Spróbuj tak:

@Query("select count(a) > 0 from Address a where (a.street = :street) or (a.street is null and :street is null)")
0
Seti87 napisał(a):

Spróbuj tak:

@Query("select count(a) > 0 from Address a where (a.street = :street) or (a.street is null and :street is null)")

to nie będzie to samo :( wtedy jak zapodasz nulową ulicę to zapytanie wskaże Ci, że jest już nulowa ulica w bazie, a nie ma.

Chyba spróbuję skorzystać z QueryDSL

1

Spróbuj takiego zapytania:

select count(a) > 0 
from Address a 
where (a.street = :street or (a.street is null and :street is null)) 
and a.city = :city 
and a.houseNumber = :houseNumber
and a.postalCode = :postalCode 

a jak chcesz wszystkie pola sprawdzać z nullem to tak:

select count(a) > 0 
from Address a 
where (a.street = :street or (a.street is null and :street is null)) 
and (a.city = :city or (a.city is null and :city is null)) 
and (a.houseNumber = :houseNumber or (a.houseNumber is null and :houseNumber is null)) 
and (a.postalCode = :postalCode or (a.postalCode is null and :postalCode is null))

1 użytkowników online, w tym zalogowanych: 0, gości: 1