Alexander Camperov
Alexander Camperov

Reputation: 393

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.

Upvotes: 31

Views: 47351

Answers (4)

Jacob Wallace
Jacob Wallace

Reputation: 927

As of Spring Data JPA 1.11.0.RELEASE, you can now use exists with query derivation from method names. For example, if you have a User entity with an email property, you can do this:

public interface UserRepository extends JpaRepository<User, Long> {

    boolean existsByEmail(String email);
}

Upvotes: 23

Adam
Adam

Reputation: 2736

@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);
}

Upvotes: 25

Oleksandr Bondarenko
Oleksandr Bondarenko

Reputation: 2018

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

Upvotes: 21

Rich Cowin
Rich Cowin

Reputation: 678

If you look at the source for org.springframework.data.jpa.repository.support.SimpleJpaRepository.exists(ID) then you will see that it uses a TypedQuery to count records and returns:

query.getSingleResult() == 1

You can create a query that does something similar for your existsBy(...) methods.

Upvotes: 2

Related Questions