Issue
I execute a SQLQuery to receive each name and count how many times this name has been called. From the query I get a list of Object types. I know the query itself is ok, tested on a databse, gets me what I want.
Desired (and received) result:
name | count |
---|---|
:name1 | :100 |
:name2 | :200 |
When I try to cast each Object object (from the result list) to my LocalClass type I get:
SEVERE: Servlet.service() for servlet [myWebService] in context with path [/myWebService] threw exception [Request processing failed; nested exception is java.lang.ClassCastException: Cannot cast [Ljava.lang.Object; to com.company.services.EmailBLImpl$1InnerClass] with root cause
java.lang.ClassCastException: Cannot cast [Ljava.lang.Object; to com.company.services.EmailBLImpl$1InnerClass
Or perhaps the question should be how to get a List<InnerClass> list
stright from the SQLquery?
The code:
@SuppressWarnings("unchecked")
@Override
public void myMethod(User user, Date dateFrom, Date dateUntil) {
@Data
class InnerClass {
private String name;
private Long count;
}
List<Object> list = sessionFactory
.getCurrentSession()
.createSQLQuery("SELECT wsService as service, count(*) as count"
+ " FROM (SELECT * FROM `table` WHERE user=" + user.getId() + ") a"
+ " GROUP BY wsService"
+ " ORDER BY count DESC")
.list();
for (Object o : list) {
// line below causes the error
InnerClass ic = InnerClass.class.cast(o);
}
}
Solution
When I try to cast
I see the problem.
That word (cast) doesn't mean what you think it means.
java has 3 operations which are completely, utterly, entirely, unrelated. guns and grandmas. Unfortunately, whilst what they do is completely unrelated, they all look the same: (SomeType) someExpr
. And that syntactic construct is called a cast.
Only one of the 3 completely unrelated things that casts do, is to convert things, and it's where the type in the parens is primitive. So, int
, double
, etcetera. All other uses of cast assert or typecheck and they cannot convert a thing. You seem to think that casts convert things. They do not, unless we're talking primitives, which Foo.class.cast()
cannot possibly be.
It is not possible to get JDBC to give you DB results in terms of your objects. Period.
Use a library that does that, such as JOOQ or JDBI.
Answered By - rzwitserloot
Answer Checked By - David Marino (JavaFixing Volunteer)