When I extend CrudRepository
interface, I have exists(ID)
method in my subinteface. I can write findBy<property>
methods.
Is it possible somehow to write existBy<property>
method that will return boolean
. Or to annotate it with @Query(jpa query)
so it will return boolean
.
I know that I can do select count(*)
and return long
, but then I will have to do !=0
check in my service layer.
Here in the following image Repository, CrudRepository and PagingAndSortingRepository belong to Spring Data Commons whereas JpaRepository belongs to Spring Data JPA. It is a base interface and extends Repository Interface. It extends PagingAndSortingRepository that extends 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.
@Oleksandr's answer is correct, but the only way I could get it to work is as follows. I'm using Eclipselink on PostgreSQL.
public interface UserRepository extends JpaRepository<User, Long> { @Query("SELECT CASE WHEN COUNT(u) > 0 THEN 'true' ELSE 'false' END FROM User u WHERE u.username = ?1") public Boolean existsByUsername(String username); }
Actually you can use case expression like this:
select case when count(e) > 0 then true else false end from Entity e where e.property = ?1 -- here go your conditions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With