Ryiad's answer DTO adds some confusion, you should have kept it away. You should have explained that it works only with hibernate.
If like me you needs to keep the order of columns, you can specify your own transformer. i copied the code from hibernate and changed the HashMap to LinkedHashMap:
import java.util.LinkedHashMap; import java.util.Map; import org.hibernate.transform.AliasedTupleSubsetResultTransformer; import org.hibernate.transform.ResultTransformer; /** * {@link ResultTransformer} implementation which builds a map for each "row", made up of each aliased value where the * alias is the map key. Inspired by {@link org.hibernate.transform.AliasToEntityMapResultTransformer}, but kepping the * ordering of elements. * <p/> * Since this transformer is stateless, all instances would be considered equal. So for optimization purposes we limit * it to a single, singleton {@link #INSTANCE instance}. */ public class AliasToEntityMapResultTransformer extends AliasedTupleSubsetResultTransformer { public static final AliasToEntityMapResultTransformer INSTANCE = new AliasToEntityMapResultTransformer(); /** * Disallow instantiation of AliasToEntityMapResultTransformer. */ private AliasToEntityMapResultTransformer() { } @Override public Object transformTuple(Object[] tuple, String[] aliases) { Map result = new LinkedHashMap<>(tuple.length); for (int i = 0; i < tuple.length; i++) { String alias = aliases[i]; if (alias != null) { result.put(alias, tuple[i]); } } return result; } @Override public boolean isTransformedValueATupleElement(String[] aliases, int tupleLength) { return false; } /** * Serialization hook for ensuring singleton uniqueing. * * @return The singleton instance : {@link #INSTANCE} */ private Object readResolve() { return INSTANCE; } }
With this transformer you can used Ryiad's solution with Hibernate:
Query jpaQuery = entityManager.createNativeQuery(queryString); org.hibernate.Query hibernateQuery =((org.hibernate.jpa.HibernateQuery)jpaQuery).getHibernateQuery(); hibernateQuery.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE); List<Map<String,Object>> res = hibernateQuery.list();
SELECT name, surname FROM usersjust to make a silly example, but it can be anything.Tupleand then you should get column/field name and value. Standard JPA API, so no real reason why a native query could not utilise it datanucleus.org/products/accessplatform_5_1/jpa/…org.hibernate.MappingException: Unknown entity: javax.persistence.Tuple