Reg*_*ser 6 java mysql spring hibernate jpa
我试图使用@Queryspring data 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 | |
+------------+---------------+------+-----+---------+-------+
Run Code Online (Sandbox Code Playgroud)
和mysql中的查询是
select last_name,count(last_name) as count from person group by last_name;
Run Code Online (Sandbox Code Playgroud)
在Spring数据jpa中实现这一点.我正在使用这个逻辑,
CountPerson包含两个变量的类,last_name和countCountPerson类对象列表.在spring数据jpa中的查询是
@Query("select p.lastName,count(p.lastName) as count from Person p group by p.lastName")
Run Code Online (Sandbox Code Playgroud)
当代码编译并且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!
Run Code Online (Sandbox Code Playgroud)
搜索此错误会显示spring数据jpa:在结果元组中找不到别名!确保您的查询定义了别名,表示它是一个固定的错误.所以我想我的问题不同了
代码是
人类
//imports
@Entity
@Table(name = "person")
public class Person{
@Id
Long id;
String firstName;
String lastName;
private Person(){}
//constructor
}
Run Code Online (Sandbox Code Playgroud)
人员存储库类
//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();
}
Run Code Online (Sandbox Code Playgroud)
控制器类
@Controller
public class PersonController{
@Autowired
PersonRepository repository;
@RequestMapping("/count")
@ResponseBody
public List<CountPerson> countbylastname(){
return repository.countbylastname();
}
}
Run Code Online (Sandbox Code Playgroud)
算人类
public class CountPerson{
String lastName;
int count;
protected CountPerson(){}
public CountPerson(String lastName,int count){
this.lastName = lastName;
this.count = count;
}
}
Run Code Online (Sandbox Code Playgroud)
Jer*_*Jun 19
差不多......(心连心,所以我希望它是完美的)你需要创建一个新的CountPerson(...)
select new com.mypackage.CountPerson(p.last_name, count(p.last_name)) from person p ...
Run Code Online (Sandbox Code Playgroud)
JpaRepository只能轻松返回Person对象,但您可以自己在HQL中创建对象.
更清晰的解决方案是使用Spring Data JPA Projections:
Yo必须替换接口的类并仅定义get方法:
public interface CountPerson {
String getLastName();
int getCount();
}
Run Code Online (Sandbox Code Playgroud)
您的Repository方法如下所示:
@Query("select p.lastName as lastName,count(p.lastName) as count from Person p group by p.lastName")
public List<CountPerson> countbylastname();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11419 次 |
| 最近记录: |