Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring data CrudRepository exists

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.

like image 877
Alexander Camperov Avatar asked Aug 29 '12 16:08

Alexander Camperov


People also ask

Is CrudRepository a part of Spring data JPA?

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.

What is true about CrudRepository and JpaRepository in Spring data JPA?

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.


2 Answers

@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); } 
like image 66
Adam Avatar answered Sep 22 '22 15:09

Adam


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 
like image 27
Oleksandr Bondarenko Avatar answered Sep 20 '22 15:09

Oleksandr Bondarenko