Spring Data JPA 有没有办法使用方法名称解析来计算实体? [英] Does Spring Data JPA have any way to count entites using method name resolving?

查看:23
本文介绍了Spring Data JPA 有没有办法使用方法名称解析来计算实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Spring Data JPA 支持实体计数使用规范.但是它有没有办法使用方法名称解析来计算实体?假设我想要一个方法 countByName 来计算具有特定名称的实体,就像一个方法 findByName 来获取具有特定名称的所有实体.

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.

推荐答案

Spring Data 1.7.1.RELEASE 开始,您可以通过两种不同的方式来实现,

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

  1. 新方法,对计数和删除查询使用查询派生.阅读这个,(例 5).例如,
  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. 老方法,使用@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);
}

另请检查这个答案.

这篇关于Spring Data JPA 有没有办法使用方法名称解析来计算实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆