如何用Criteria实现指定字段查询并返回对象数组而非Entity列表?
Got it, let's work through this problem—you want to use Hibernate Criteria to pull specific fields (like id and field1) as an array of objects instead of full Entity instances, right? This is totally achievable with projections, and I'll walk you through the exact steps to make it work.
1. Core Implementation with Projections
The key here is using Projections to explicitly define which fields you want to fetch, instead of loading the entire entity. Here's the code:
Session session = sessionFactory.getCurrentSession(); Criteria criteria = session.createCriteria(Entity.class); // Define the fields you want to retrieve using a projection list criteria.setProjection(Projections.projectionList() .add(Projections.id()) // Fetches the entity's primary key (index 0 in the array) .add(Projections.property("field1"))); // Fetches field1 (index 1 in the array) // Execute the query to get your list of object arrays List<Object[]> results = criteria.list();
How this works:
Projections.projectionList()lets you assemble multiple fields to include in your result set.- Each projection you add is mapped to an element in the
Object[]in the exact order you add them—soidlands at index 0,field1at index 1. - If you prefer explicit naming for the id, you can replace
Projections.id()withProjections.property("id")(just make sure it matches the field name in yourEntityclass).
2. Optional: Add Aliases for Readability
If you want cleaner code (or need to reference fields for sorting/filtering), you can assign aliases to each projection:
criteria.setProjection(Projections.projectionList() .add(Projections.id(), "entityId") .add(Projections.property("field1"), "entityField1")) .addOrder(Order.asc("entityId")); // Example: sort by the aliased id
Aliases don't change the index positions in the result array—they just make your criteria setup more readable and flexible.
3. Working with the Results
Once you have the List<Object[]>, iterate through it and cast each element to the correct data type for your entity's fields:
for (Object[] result : results) { Long entityId = (Long) result[0]; // Cast to your actual id type (Integer, Long, etc.) String entityField1 = (String) result[1]; // Cast to the type of field1 // Do whatever you need with these values }
Just double-check the data types here—mismatched casts will throw ClassCastExceptions.
Common Mistakes to Avoid
- Skipping Projections: If you forget
setProjection(), Criteria will default to returning fullEntityobjects instead of arrays. This is likely why your earlier attempts didn't work! - Typos in Field Names: Make sure the property names ("id", "field1") exactly match the field names in your
Entityclass (case-sensitive in most configurations). - Incorrect Type Casts: Always verify the data type of each field in your entity before casting the array elements.
内容的提问来源于stack exchange,提问作者Vinicius Silva

