- 先把entityManager.createNativeQuery生成的jpa接口的Query 强转为hibernateQuery 的query
- 然后就可以调用hibernate的方法,设置属性,返回的list结果就是Map<String,Object>的有列名称columnName的对象
- 然后用jackson的ObjectMapper().convertValue把map转换为pojo对象
- 基本和jdbctemplate一样了
//第一种 tuple
Query query = entityManager.createNativeQuery("select * from proj limit 12;", Tuple.class);
List<Tuple> tuples = query.getResultList();
List<Map<String, Object>> result = new ArrayList<>();
for (Tuple single : tuples) {
Map<String, Object> tempMap = new HashMap<>();
for (TupleElement<?> key : single.getElements()) {
tempMap.put(key.getAlias(), single.get(key));
}
result.add(tempMap);
}
// tuple 转对象
List<Proj> projs = tuples.stream().map(t -> {
Proj p=new Proj();
p.setId(Long.valueOf(t.get(0, BigInteger.class).toString()));
p.setProname(t.get("proname", String.class));
return p;
}).collect(Collectors.toList());
//第二种
org.hibernate.query.Query query = entityManager.createNativeQuery("select * from proj limit 10;").unwrap(org.hibernate.query.Query.class);
query.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
List<Map<String,Object>> result = query.list();