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

后端 未结 12 832
耶瑟儿~
耶瑟儿~ 2020-12-04 08:38

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 cou

相关标签:
12条回答
  • 2020-12-04 09:16

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

    0 讨论(0)
  • 2020-12-04 09:27
    @Autowired
    private UserRepository userRepository;
    
    @RequestMapping("/user/count")
    private Long getNumberOfUsers(){
        return userRepository.count();
    }
    
    0 讨论(0)
  • 2020-12-04 09:31

    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));
    
    0 讨论(0)
  • 2020-12-04 09:31

    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

    0 讨论(0)
  • 2020-12-04 09:34

    According to the issue DATAJPA-231 the feature is not implemented yet.

    0 讨论(0)
  • 2020-12-04 09:35

    Apparently it is implemented now DATAJPA-231

    0 讨论(0)
提交回复
热议问题