简体   繁体   中英

executing case expressions in jpql

I'm learning JPA and doing some hands one with JPQL. I am having trouble in CASE expressions. For example, this query,

Query caseQuery = em
            .createQuery("SELECT t , CASE WHEN t.salary = 20000 THEN '20k' WHEN t.salary = 40000 THEN '40k' ELSE 'No salary' END FROM Teacher t");

and executing it using

List<Teacher> teachers = (List<Teacher>) caseQuery.getResultList();

but whenever I try to print the results out, I'm getting ClassCastException that Object cannot be converted to Teacher

I've tried using TypedQuery for Teacher but it didn't work. Could you experts please throw some light on executing this CASE statements in JPQL?

The reason is due to multiple select expressions in your query and not due to CASE Expression ,I believe with multiple select expressions the result will be Object[] rather than translated to the Entity. Some references JPA Tutorial ; JPQL . A related query already in stack overflow .

You should modify

List<Teacher> teachers = (List<Teacher>) caseQuery.getResultList();

to

List<Object[]> teachers = (List<Object[]>) caseQuery.getResultList();

where Object[] will be an array of Teacher & String

For TypedQuery also similar change should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM