31

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.

dur
  • 15,689
  • 25
  • 79
  • 125
Alexander Camperov
  • 393
  • 2
  • 5
  • 11
  • 1
    "but then I will have to do !=0 check in my service layer." Also using exist instead of count would be slightly more efficient for db query – WeGa Jul 04 '16 at 10:12

4 Answers4

25

@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);
}
Adam
  • 2,616
  • 33
  • 29
23

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);
}
Jacob Wallace
  • 887
  • 2
  • 12
  • 24
21

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
Oleksandr Bondarenko
  • 1,998
  • 1
  • 19
  • 22
2

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.

Rich Cowin
  • 668
  • 1
  • 8
  • 17
  • 1
    yeah, I looked in the source code. By then I'll have to implement my Dao interface. I was looking for solution when I wont have to do that =) – Alexander Camperov Aug 30 '12 at 07:01