**已关闭。**此问题需要debugging details。目前不接受回答。
编辑问题以包括desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将帮助其他人回答问题。
12天前关闭
Improve this question的
我正在使用Sping Boot ,希望使用@Query()annotation返回我Employee类的所有列表,但它返回了异常:这里是我的代码//这里是我的存储库类
package com.employee.Dao;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.employee.Entities.Employee;
@Repository
public interface UserRepository extends CrudRepository<Employee,Long> {
@Query("select e FROM Employee e")
public <List>Employee getAllEmployee();
@Query(value = " From Employee e where e.fullName=:name")
public <List>Employee getEmployeeByName(@Param("name") String name);
}
字符串
下面是我的控制器类
@GetMapping("/main")
public String main(@ModelAttribute Employee employee, ModelMap model, HttpSession session) {
List<Employee> allEmployeeQuery = this.empservice.getAllEmployeeQuery();
allEmployeeQuery.forEach(a->System.out.println(a));
return "main";
}
型
我想使用@Query()annotation获取allEmploy的列表,但它抛出了一个异常。
[2m[nio-8080-exec-1][0;39m [36mo.a.c.c.C.[.[.[/].[dispatcherServlet] [0;39m [2m:[0;39m Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: java.lang.ClassCastException: class com.employee.Entities.Employee cannot be cast to class java.util.List (com.employee.Entities.Employee is in unnamed module of loader 'app'; java.util.List is in module java.base of loader 'bootstrap')] with root cause
java.lang.ClassCastException: class com.employee.Entities.Employee cannot be cast to class java.util.List (com.employee.Entities.Employee is in unnamed module of loader 'app'; java.util.List is in module java.base of loader 'bootstrap')
at com.employee.service.EmpService.getAllEmployeeQuery(EmpService.java:22) ~[classes/:na]
at com.employee.MainController.main(MainController.java:37) ~[classes/:na]
型
Sping Boot 和Hibernate
2条答案
按热度按时间q7solyqu1#
你应该提到哪些字段或字段需要作为结果。看起来你只有
ClassCastException
与第二个查询,因为你没有提到你需要在结果中的细节,但在查询中设置<List>Employee
返回类型。用这个更新你的查询并尝试。它可能解决你的
ClassCastException
问题。字符串
p8h8hvxi2#
除了@Mark Rotteveel在关于
List<Employee>
而不是<List>Employee
的评论中所说的之外,请记住,因为您在项目中使用了spring-boot-starter-data-jpa依赖项,所以您甚至不需要使用@Query进行简单的查询。您可以在UserRepository中定义以下单行代码,Spring Data JPA将自动创建查询:
字符串
只要你在UserRepository中实现了CrudRepository或JpaRepository,你就可以免费获得一大堆基本的CRUD操作查询。所以在你的仓库之外,你可以做:
型
此外,它是挑剔的,但UserRepository绝对应该被重命名为BaseRepository。