SpringJPA的entityManager执行原生SQL

//构造SQL,查询结果加上\"不然查询结果都是大写映射不上实体字段
String sql = "select \"id\",\"name\" from tableName where id = :id"
//构造查询和返回结果到指定VO,返回到map就用Transformers.ALIAS_TO_ENTITY_MAP
NativeQueryImplementor nativeQuery = this.entityManager.createNativeQuery(sql).
												unwrap(NativeQueryImpl.class).
												setResultTransformer(Transformers.aliasToBean(ViewAlarmCount.class));
//设置参数										
nativeQuery.setParameter("id",id);
//设置返回结果类型(不设置有时候会报错)
nativeQuery.addScalar("id", StandardBasicTypes.LONG);
nativeQuery.addScalar("name", StandardBasicTypes.STRING);
//请求结果
List<ViewAlarmCount> resultList = nativeQuery.getResultList();

你可能感兴趣的:(hibernate)