In JPA 2.0, we can use entityManager.createNativeQuery() to execute native SQL statements. But when our query result does not have a corresponding entity class, query.getResultList() returns a List<Object[]>. That is to say, the data of each row is returned as an object array.
The common usage is this:
public void testNativeQuery(){ Query query = entityManager.createNativeQuery("select id, name, age from t_user"); List rows = query.getResultList(); for (Object row : rows) { Object[] cells = (Object[]) row; System.out.println("id = " + cells[0]); System.out.println("name = " + cells[1]); System.out.println("age = " + cells[2]); }}This way, it will make the code very difficult to understand. What exactly is an element with a subscript of 0? It is not known if you don’t count the query statement. Moreover, once the query statement is adjusted, the Java code must also be adjusted together. At this time, we think that if the map is returned, it will be much clearer to use.
Unfortunately, JPA's API does not provide such a setting. In fact, many underlying JPA implementations support returning Map objects.
For example:
EclipseLink's query.setHint(QueryHints.RESULT_TYPE, ResultType.Map); Hibernate's .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
So, if we want to return the map and determine that the underlying layer is using a certain JPA implementation, we can take the next step and sacrifice cross-implementation features to meet our needs:
public void testNativeQuery(){ Query query = entityManager.createNativeQuery("select id, name, age from t_user"); query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); List rows = query.getResultList(); for (Object obj : rows) { Map row = (Map) obj; System.out.println("id = " + row.get("ID")); System.out.println("name = " + row.get("NAME")); System.out.println("age = " + row.get("AGE")); }}Query returns the writing method of the specified entity return type
Query query = entityManager.createNativeQuery("select id, name, age from t_user", User.Class);It should be noted here that using Map is definitely less efficient than using Object arrays. So you have to see if the performance drop is within the acceptable range. Then, in my Hibernate 4.2.x environment, no matter whether you write capital letters or lowercase letters in your native SQL, the returned field names are capitalized. Of course, you can process the field names in a certain way by customizing the ResultTransformer, and even return the POJO you need.
The above method to let JPA's Query query interface return Map object is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.