Search code examples
javaspring-boothibernatenhibernate-mapping

Exception when use @Query () to return list of Employee


i am using spring boot want to return all list of my Employee class using @Query() annotation but it returns exception here is my code //here is my repository clas

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);

}

Here is my controller class

@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";
}

I want to get list of allEmploy using @Query() annotation but it throws an exception. Here are the details of the exception

[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]

I am using Spring Boot and Hibernate.


Solution

  • You should mention which field OR fields you need as result. It looks like you only have ClassCastException with second query because you didn't mention which details you need in result but set <List>Employee return type in query.

    Update your query with this and try. It might solve your ClassCastException

    @Query(value = "SELECT e FROM Employee e WHERE e.fullName = :name")
    public List<Employee> getEmployeeByName(@Param("name") String name);