一尘不染

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

hibernate

我正在尝试使用@Queryspring数据jpa 的注释在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. 创建另一个CountPerson包含两个变量的类,last_namecount
  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<Person,Long>{

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

控制器类

@Controller
public class PersonController{

    @Autowired
    PersonRepository repository;

    @RequestMapping("/count")
    @ResponseBody
    public List<CountPerson> 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;
    }
}

阅读 627

收藏
2020-06-20

共1个答案

一尘不染

快到了…(顺便说一句,所以我希望它是完美的)您需要创建一个新的CountPerson(…)

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

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

2020-06-20