Spring Data JPA supports counting entities using specifications. But does it have any way to count entities using method name resolving? Let's say I want a method countByName
to count entities with specific name, just like a method findByName
to fetch all entities with specific name.

- 18,813
- 9
- 90
- 92

- 1,889
- 2
- 12
- 4
-
7Please accept one of the answers, YaoFeng. I have tested Spring Data JPA 1.5.2 and the countByName() syntax works as Abel notes. – nullPainter Apr 30 '14 at 04:58
13 Answers
As of Spring Data 1.7.1.RELEASE you can do it with two different ways,
- 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);
}
- 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.

- 12,304
- 8
- 54
- 77

- 18,813
- 9
- 90
- 92
-
3
-
1The question was about the count function, not sum or average. Spring data does not support something like the 'new way' for this functions yet. You could use something like [this](http://stackoverflow.com/questions/3449719/how-to-run-an-aggregate-function-like-sum-on-two-columns-in-jpa-and-display-thei) – Georgios Syngouroglou Apr 26 '15 at 20:13
-
1In your second and third examples, I think you would need to use "SELECT COUNT(u)...", since this is supposed to be a count query. – TheChrisPratt Nov 13 '15 at 20:55
-
-
I'll add `Long countByNameIn(List
names);` if that can help others, when counting different values – Jad B. Apr 16 '20 at 12:25 -
Didn't work for me with MariaDB until I changed the query string to `SELECT COUNT(*) FROM User WHERE u.name=:name` does (using asterisk). Database error was: `Error in query (1054): Unknown column 'u' in 'field list'` – snaeil Mar 07 '22 at 14:22
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);

- 3,094
- 1
- 14
- 11
-
4note that the method should return `long` instead of `int`, otherwise you will get a ClassCastException without any clues – Rangi Lin Feb 21 '14 at 06:26
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));

- 4,432
- 1
- 36
- 44
-
1This version I like most - especially since I couldn't make a clue how this should work according to the docu :-) You saved my day :-) As a remark: Primitives (e.g. int) are included in the expamle-search, i.e. `int age` will be included although not set, but `Integer age` will be excluded from the sample (at least in Eclipselink) – LeO Oct 12 '17 at 06:28
-
1
Working example
@Repository
public interface TenantRepository extends JpaRepository< Tenant, Long > {
List<Tenant>findByTenantName(String tenantName,Pageable pageRequest);
long countByTenantName(String tenantName);
}
Calling from DAO layer
@Override
public long countByTenantName(String tenantName) {
return repository.countByTenantName(tenantName);
}

- 4,843
- 8
- 35
- 55

- 145
- 1
- 6
According to Abel, after the version 1.4 (tested in version 1.4.3.RELEASE) is possible doing this way:
public long countByName(String name);

- 1,265
- 12
- 12
Thanks you all! Now it's work. DATAJPA-231
It will be nice if was possible to create count…By… methods just like find…By ones. Example:
public interface UserRepository extends JpaRepository<User, Long> {
public Long /*or BigInteger */ countByActiveTrue();
}

- 311
- 2
- 5
@Autowired
private UserRepository userRepository;
@RequestMapping("/user/count")
private Long getNumberOfUsers(){
return userRepository.count();
}

- 61
- 5
-
1This example is out of topic. The user asked how to countBy field name and not how to call the basic count from a REST service. – Jad B. Apr 16 '20 at 12:18
I have only been working with it for a few weeks but I don't believe that this is strictly possible however you should be able to get the same effect with a little more effort; just write the query yourself and annotate the method name. It's probably not much simpler than writing the method yourself but it is cleaner in my opinion.
Edit: it is now possible according to DATAJPA-231

- 1,273
- 2
- 18
- 32
According to the issue DATAJPA-231 the feature is not implemented yet.

- 1,998
- 1
- 19
- 22
If anyone wants to get the count based on multiple conditions than here is a sample custom query
@Query("select count(sl) from SlUrl sl where sl.user =?1 And sl.creationDate between ?2 And ?3")
long countUrlsBetweenDates(User user, Date date1, Date date2);

- 6,548
- 8
- 42
- 69
In my opinion the other solutions do not answer the question. According to the sentence
Spring Data JPA supports counting entities using specifications.
he wants to use JPA Specifications with name resolving. All the answers are pointing to the api without specifications.
As long as I know there is no repository implementation with specification and name resolving. The JpaSpecificationExecutor does not support it.
I had the same problem and created a custom repository where I used code like:
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Long> query = builder.createQuery(Long.class);
Root<S> root = query.from(domainClass);
Path<Object> attribute = root.get(attributeName);
query.select(builder.countDistinct(attribute));
if(spec == null){
return em.createQuery(query);
}
Predicate predicate = spec.toPredicate(root, query, builder);
if(predicate != null){
query.where(predicate);
}
return em.createQuery(query);
The variable "attributeName" is a String with the name of the attribute.

- 11
- 4