Jar*_*cki 0 java spring jpa count spring-boot
我在从自定义查询访问数据时遇到问题。
这是 POJO:
@Getter
@Setter
@NoArgsContructor
@AllArgsConstructor
@Entity
@Table(name = "run_list")
public class RunList {
@Id
@Column(name = "id")
private Long id;
@Column(name = "control_run_name"
private String serverName;
@Column(name = "control_run_date"
private Date controlRunDate
<.. bunch of other fields .. >
Run Code Online (Sandbox Code Playgroud)
这是存储库:
public interface RunListRepository extends JpaRepository<RunList, Long> {
@Query("SELECT u.serverName,count(u) as controlRunCount from RunList u where u.controlRunDate < :lastUploadDate group by u.serverName")
List<RunList> findAllControlRunAfterDate(@Param("lastUploadDate") Date lastUploadDate);
Run Code Online (Sandbox Code Playgroud)
在控制器中,我像这样调用存储库方法:
Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2020-03-01");
model.addAttribute("runList",runListRepository.findAllControlRunAfterDate(date);
Run Code Online (Sandbox Code Playgroud)
与查询中日期的绑定工作正常,我得到了分组的第一个结果,这样问题就解决了。问题是我在运行此命令时遇到错误:
Failed to convert from type[java.lang.Object[]] to type [@org.springframework.data.jpa.Query my.package.name.RunList} for value '{server1,14}';
Run Code Online (Sandbox Code Playgroud)
当我从 CLI 中对数据库使用 SQL 查询时,我得到了服务器名称和计数的良好分组。我猜测问题在于计数字段的转换,该字段从存储库方法中突然弹出,而 Spring 也不知道要链接什么。
我尝试在这里使用仅具有 String serverName 和 Ingeter controlRunCount 的 RunListDTO,但没有成功 - 存储库接口不喜欢我在使用 . 创建的接口中使用的方法的输出中使用 DTO。
当存储库进行计数时,有没有办法使其成为飞行中的自定义数组/对象?
问候,贾雷克。
小智 5
由于您选择一个字段和一个计数,因此无法将其映射到您的实体,因此此查询返回您指定的值的数组,就像您在异常中看到的那样: ' { server1,14}'。
public interface RunListRepository extends JpaRepository<RunList, Long> {
@Query("SELECT u.serverName,count(u) as controlRunCount from RunList u where u.controlRunDate < :lastUploadDate group by u.serverName")
List<Object[]> findAllControlRunAfterDate(@Param("lastUploadDate") Date lastUploadDate);
Run Code Online (Sandbox Code Playgroud)
因此,在您的服务中,您可以使用这些数据,例如:
List<Object[]> list = runListRepository.findAllControlRunAfterDate(yourDate);
for (Object[] ob : list){
String serverName = (String)ob[0];
Integer count = (Integer)ob[1];
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7223 次 |
| 最近记录: |