Does Spring Data JPA have any way to count entites using method name resolving? Does Spring Data JPA have any way to count entites using method name resolving? java java

Does Spring Data JPA have any way to count entites using method name resolving?


As of Spring Data 1.7.1.RELEASE you can do it with two different ways,

  1. The new way, using query derivation for both count and delete queries. Read this, (Example 5).Example,
    public interface UserRepository extends CrudRepository<User, Integer> {        long countByName(String name);    }
  1. The old way, Using @Query annotation.
    Example,
    public interface UserRepository extends CrudRepository<User, Integer> {        @Query("SELECT COUNT(u) FROM User u WHERE u.name=?1")        long aMethodNameOrSomething(String name);    }

or using @Param annotation also,

public interface UserRepository extends CrudRepository<User, Integer> {    @Query("SELECT COUNT(u) FROM User u WHERE u.name=:name")    long aMethodNameOrSomething(@Param("name") String name);}

Check also this so answer.


As long as you do not use 1.4 version, you can use explicit annotation:

example:

@Query("select count(e) from Product e where e.area.code = ?1")long countByAreaCode(String code);


JpaRepository also extends QueryByExampleExecutor. So you don't even need to define custom methods on your interface:

public interface UserRepository extends JpaRepository<User, Long> {    // no need of custom method}

And then query like:

User probe = new User();u.setName = "John";long count = repo.count(Example.of(probe));