Reputation: 191
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.
Upvotes: 0
Views: 1520
Reputation: 502
In JPQL, the SELECT clause defines what object types you want to retrieve from the database. Instead of querying for the fields, you should query for the whole object like this:
SELECT func FROM Function func
You can find more information and examples at The Java EE 6 Tutorial.
Upvotes: 0
Reputation: 2711
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();
Upvotes: 1
Reputation: 1233
when selecting individual columns you don't get the Type (Function in your case) but an array of Objects, like: Object[]
.
So try: List<Object[]> findItAll();
Or if fetching all columns is ok you can do it like Doleron's answer.
Upvotes: 1
Reputation: 44515
You are only selecting two fields of your entities:
func.functionId, func.functionName
That means, the query will return a list of object arrays, each with two elements, which you then try to cast to a list of Function objects. That doesn't work. Either add a mapping step in between or select the whole entity in your query.
Upvotes: 0