Spring Data JPA支持使用规范计算实体。但它有没有办法使用方法名称解析来计算实体?假设我想要一个方法countByName
来计算具有特定名称的实体,就像方法findByName
一样,以获取具有特定名称的所有实体。
答案 0 :(得分:159)
从 Spring Data 1.7.1.RELEASE 开始,您可以通过两种不同的方式来实现,
1)新方式,使用查询推导计数和删除查询。阅读this,(例5)。 例如,
public interface UserRepository extends CrudRepository<User, Integer> {
Long countByName(String name);
}
2)旧方式,使用@Query注释 例如,
public interface UserRepository extends CrudRepository<User, Integer> {
@Query("SELECT COUNT(u) FROM User u WHERE u.name=?1")
Long aMethodNameOrSomething(String name);
}
或使用@Param注释,
public interface UserRepository extends CrudRepository<User, Integer> {
@Query("SELECT COUNT(u) FROM User u WHERE u.name=:name")
Long aMethodNameOrSomething(@Param("name") String name);
}
同时检查this so answer。
答案 1 :(得分:15)
只要您不使用1.4版本,就可以使用显式注释:
示例:
@Query("select count(e) from Product e where e.area.code = ?1")
int countByAreaCode(String code);
答案 2 :(得分:10)
1.4版M1
中添加了此功能答案 3 :(得分:7)
JpaRepository还扩展了QueryByExampleExecutor。因此,您甚至不需要在界面上定义自定义方法:
public interface UserRepository extends JpaRepository<User, Long> {
// no need of custom method
}
然后查询:
User probe = new User();
u.setName = "John";
long count = repo.count(Example.of(probe));
答案 4 :(得分:5)
根据Abel的说法,在版本1.4(在版本1.4.3.RELEASE中测试)之后可以这样做:
public long countByName(String name);
答案 5 :(得分:4)
显然它现在已经实施DATAJPA-231
答案 6 :(得分:4)
工作示例
@Repository
public interface TenantRepository extends JpaRepository< Tenant, Long > {
List<Tenant>findByTenantName(String tenantName,Pageable pageRequest);
long countByTenantName(String tenantName);
}
从DAO层调用
@Override
public long countByTenantName(String tenantName) {
return repository.countByTenantName(tenantName);
}
答案 7 :(得分:1)
根据问题DATAJPA-231,该功能尚未实施。
答案 8 :(得分:1)
谢谢大家!现在它的工作。 DATAJPA-231
如果有可能创造计数......那将是很好的...通过...方法就像找到...由一些。例如:
public interface UserRepository extends JpaRepository<User, Long> {
public Long /*or BigInteger */ countByActiveTrue();
}
答案 9 :(得分:0)
我只与它合作了几个星期,但我不相信这是严格可能的,但是你应该能够通过更多的努力获得同样的效果;只需自己编写查询并注释方法名称。它可能并不比自己编写方法简单得多,但在我看来它更清晰。
答案 10 :(得分:0)
@Autowired
private UserRepository userRepository;
@RequestMapping("/user/count")
private Long getNumberOfUsers(){
return userRepository.count();
}
答案 11 :(得分:0)
如果有人想基于多个条件获取计数,那么这里是一个示例自定义查询
@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);