关于Criteria与HQL查询返回值的技术咨询
Return Value Differences Between Your HQL and Criteria Queries
Hey there, let's break down the key differences in return values between these two queries, plus point out some critical mismatches in your current code:
1. Element Type & Method Signature Mismatches
First, let's clarify what each query actually returns vs. what your method declarations claim:
HQL Query
Your HQL code:
Query<Object[]> query = manager.getSession().createQuery("select user.firstName from User user",Object[].class); return query.getResultList();
- Actual return content: Since you're only selecting a single field (
firstName, likely aString), Hibernate won't wrap this value in anObject[]. Each element in the list is just the rawfirstNamescalar value (e.g., aStringor whatever type yourfirstNameis mapped to). - Method signature issue: Your method says it returns
List<Object[]>, but this is incorrect. The real return type should beList<String>(orList<Object>for generic use). UsingObject[].classhere will cause a runtime type mismatch.
Criteria Query
Your Criteria code snippet:
Criteria criteria = manager.getSession().createCriteria(User.class).setProjection(P... return criteria.list(); // Method declares return type List<User>
- Actual return content: As soon as you add a
Projection(likeProjections.property("firstName")), Hibernate stops returning fullUserentity objects. Instead, it returns just the projected field value (again, aStringforfirstName). - Method signature issue: Your method claims to return
List<User>, but this is wrong when using projections. You'll hit aClassCastExceptionat runtime if you try to cast the returned string values toUserobjects.
2. Content of List Elements
- HQL: Even with the incorrect signature, each element in the list is a single scalar value (the
firstNamestring). If you selected multiple fields (e.g.,select user.firstName, user.lastName), then each element would be anObject[]holding those two values—but that's not your current query. - Criteria: With projections enabled, each element is a single scalar value (the projected field). If you removed the projection entirely, it would return full
Userentities, but your code explicitly starts withsetProjection(...), so that's not the case here.
3. Type Safety Fixes
To make both queries type-safe and align their return values with reality:
- Fixed HQL:
@Override public List<String> getAllLoginHQL() { Query<String> query = manager.getSession().createQuery("select user.firstName from User user", String.class); return query.getResultList(); } - Fixed Criteria:
@Override public List<String> getAllLoginCriteria() { Criteria criteria = manager.getSession().createCriteria(User.class) .setProjection(Projections.property("firstName")); return (List<String>) criteria.list(); }
内容的提问来源于stack exchange,提问作者Suule
相关产品推荐
相关产品推荐

