JDBC新手技术问询:如何从HQL查询返回的Query对象中获取数据?
Hey there! Since you're new to working with HQL and JPA's Query interface, let's walk through exactly how to extract your query results clearly and safely.
Option 1: Retrieve Results as an Array of Objects (Quick & Simple)
Your HQL query selects two specific fields (appkey and type), so the Query will return a List<Object[]> where each array represents a single row of results. Each element in the array maps to the fields in your query order.
Here's how to use it:
// Execute the query and get the result list List<Object[]> results = query.getResultList(); // Iterate through each row for (Object[] row : results) { // Cast elements to the correct data types (match your entity's field types) String appkey = (String) row[0]; String type = (String) row[1]; // Adjust this if your `type` is an Integer or another type // Do something with the data (e.g., print, store in a collection, etc.) System.out.printf("Appkey: %s | Type: %s%n", appkey, type); }
Option 2: Use a DTO for Type-Safe Results (Cleaner & Maintainable)
For more readable and type-safe code, create a simple Data Transfer Object (DTO) to hold your query results. This avoids casting Object[] and makes your code easier to follow.
- First, create the DTO class:
// Replace com.yourpackage with your actual package path public class AppInfoDTO { private String appkey; private String type; // Constructor must match the order of fields in your HQL query public AppInfoDTO(String appkey, String type) { this.appkey = appkey; this.type = type; } // Add getters (and setters if needed) public String getAppkey() { return appkey; } public String getType() { return type; } }
- Update your HQL query to use the DTO:
// Use the fully qualified class name of your DTO in the HQL final String hql = "select new com.yourpackage.AppInfoDTO(app.appkey, app.type) from " + getClassName() + " app where app.appkey<>'no-appkey' group by app.type"; Query query = getEntityManager().createQuery(hql); // Now you can get a list of your DTO directly List<AppInfoDTO> appInfoList = query.getResultList(); for (AppInfoDTO appInfo : appInfoList) { System.out.printf("Appkey: %s | Type: %s%n", appInfo.getAppkey(), appInfo.getType()); }
Bonus: Getting a Single Result
If you expect only one row from your query, you can use getSingleResult() instead of getResultList(). Just be aware this will throw an exception if there are 0 or more than 1 results, so it's safe to pair it with setMaxResults(1):
query.setMaxResults(1); try { Object[] singleResult = (Object[]) query.getSingleResult(); String appkey = (String) singleResult[0]; String type = (String) singleResult[1]; // Handle the single result } catch (NoResultException | NonUniqueResultException e) { // Handle cases where there's no result or too many results e.printStackTrace(); }
内容的提问来源于stack exchange,提问作者Shuitian Wei

