StringBuilder strb = new StringBuilder();
strb.append(" select * from dual ");
EntityManager bizManager =commonNativeOperateService.getBizManager();
Query query = bizManager.createNativeQuery(strb.toString());
query.unwrap(SQLQuery.class).addScalar("productType",StandardBasicTypes.STRING)
.addScalar("policyNo").addScalar("quotaApplyNo")
.addScalar("corpId").addScalar("payMode")
.addScalar("payTerm",StandardBasicTypes.DOUBLE).addScalar("quotaSum")
.addScalar("buyerNo").addScalar("bankNo").addScalar("buyerGroupCode")
.addScalar("bankGroupCode").addScalar("buyerCountryCode")
.addScalar("bankCountryCode").addScalar("reNewalEndorseNo")
.addScalar("endorseDetailNo") .addScalar("isReInsured",StandardBasicTypes.STRING)
.addScalar("unReInsuredReason").addScalar("reInsureRatio",StandardBasicTypes.DOUBLE)
.setResultTransformer(Transformers.aliasToBean(ReQuotaApply.class));
query.setParameter(1, quotaApplyNo);
List resultList = query.getResultList();
以上代码中:
1.addScalar():确定返回字段与类型
2.setResultTransformer():确定返回对象类型
3.但是:hibernate 5.2 之后,SQLQuery.class、setResultTransformer方法已作废,其用法如下:
a.旧代码:
Query query = entityManager.createNativeQuery(sql, clazz);
query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
b.替换为:
Query query = entityManager.createNativeQuery(sql, clazz);
query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);