Search code examples
javahibernatejpql

Java.lang.Object; cannot be cast to <hibernate entity>


So - I'm new to hiberate and Java in general. I've seen a couple threads in regards to this error, but none seem to fit my situation. I have a simple JPQL query as shown below that should returnthe function ID and name from the Function table/entity. This query is held within my FunctionRepository.java

@Query("SELECT func.functionId, func.functionName"
    + " FROM Function func")
List<Function> findItAll();



-----below is my FunctionService.java-------



public ArrayNode getAllFunctions() {
    ArrayNode json = null;
    try {
        List<Function> functions = (List<Function>) functionRepository.findItAll();
        json = crudEntitiesToJson(functions);
    } catch (CorruptDataException cdEx) {
        logger.error(cdEx.getMessage());
    }

    return json;
}

The "crudEntitiesToJson" method is the following;

private ArrayNode crudEntitiesToJson(Iterable<Function> entities) throws CorruptDataException {
    ArrayNode result = new ArrayNode(JsonNodeFactory.instance);
    for (Function entity : entities) {
        result.add(FunctiontoJson(entity));
    }
    return result;
}

And all of this is kicked off by my FunctionController.java

The project builds and runs fine, but when I try to hit the endpoint that kicks off that query I get the following error:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.ge.starfish.entity.Function

I guess Im confused as to where I'm going wrong.

Thanks in advance.


Solution

  • Change for

    @Query("SELECT func FROM Function func") 
    List<Function> findItAll();
    

    to retrieve all Functions instead of a array with the two attributes. it would also works:

    @Query("FROM Function") 
    List<Function> findItAll();