Spring数据JPA:在结果元组中找不到别名! 执行自定义查询时出错

我正在尝试使用spring数据jpa的@Query注释在mysql数据库上执行自定义查询。

表是

 +------------+---------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +------------+---------------+------+-----+---------+-------+ | id | decimal(10,0) | NO | PRI | NULL | | | first_name | varchar(20) | YES | | NULL | | | last_name | varchar(20) | YES | | NULL | | +------------+---------------+------+-----+---------+-------+ 

和mysql中的查询是

 select last_name,count(last_name) as count from person group by last_name; 

在Spring数据jpa中实现这一点。 我正在使用这个逻辑,

  1. 创建另一个包含两个变量last_namecount CountPerson
  2. 使用@Query编写查询,该方法返回CountPerson类的对象列表。

在spring数据jpa中的查询是

 @Query("select p.lastName,count(p.lastName) as count from Person p group by p.lastName") 

当代码编译并且Web服务器启动正常时,当我尝试运行相关方法时,我得到了

 There was an unexpected error (type=Internal Server Error, status=500). No aliases found in result tuple! Make sure your query defines aliases!; nested exception is java.lang.IllegalStateException: No aliases found in result tuple! Make sure your query defines aliases! 

搜索此错误会显示spring数据jpa:在结果元组中找不到别名! 确保您的查询定义了别名 ,表示它是一个固定的错误。 所以我猜我的问题不同了


代码是

人类

 //imports @Entity @Table(name = "person") public class Person{ @Id Long id; String firstName; String lastName; private Person(){} //constructor } 

人员存储库类

 //imports @Transactional public interface PersonRepository extends CrudRepository{ @Query("select p.lastName,count(p.lastName) as count from Person p group by p.lastName") public List countbylastname(); } 

控制器类

 @Controller public class PersonController{ @Autowired PersonRepository repository; @RequestMapping("/count") @ResponseBody public List countbylastname(){ return repository.countbylastname(); } } 

算人类

 public class CountPerson{ String lastName; int count; protected CountPerson(){} public CountPerson(String lastName,int count){ this.lastName = lastName; this.count = count; } } 

差不多……(心连心,所以我希望它是完美的)你需要创建一个新的CountPerson(…)

 select new com.mypackage.CountPerson(p.last_name, count(p.last_name)) from person p ... 

JpaRepository只能轻松返回Person对象,但您可以自己在HQL中创建对象。

更清晰的解决方案是使用Spring Data JPA Projections :

Yo必须替换接口的类并仅定义get方法:

 public interface CountPerson { String getLastName(); int getCount(); } 

您的Repository方法如下所示:

 @Query("select p.lastName as lastName,count(p.lastName) as count from Person p group by p.lastName") public List countbylastname();