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

时间:2017-02-23 15:01:30

标签: java mysql spring hibernate jpa

我正在尝试使用弹簧数据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. 创建另一个包含两个变量CountPersonlast_name
  2. 的班级count
  3. 使用@Query编写查询,该方法返回CountPerson类对象列表。
  4. 弹簧数据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 data jpa: No aliases found in result tuple! Make sure your query defines aliases,表明这是一个固定的错误。所以我想我的问题是不同的

    代码是

    人类

    //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 个答案:

答案 0 :(得分:5)

更干净的解决方案是使用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<CountPerson> countbylastname();