当前位置: 首页 > 知识库问答 >
问题:

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

白坚壁
2023-03-14

我试图使用spring data 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    |       |
+------------+---------------+------+-----+---------+-------+
select last_name,count(last_name) as count from person group by last_name;
    null
@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;
    }
}

共有1个答案

宫元徽
2023-03-14

快到了...(记住了,所以我希望它是完美的)你需要创建一个新的CountPerson(...)

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

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

 类似资料: