- 采用问号
?
方式传参
@PersistenceContext
private EntityManager entityManager;
@Override
public CustomApproval findApprovalById(Integer id) {
// TODO Auto-generated method stub
String sql = "select expiresAt,status,lastModifiedAt as lastUpdatedAt,userId,clientId,scope from oauth_approvals where id=?";
Query query = entityManager.createNativeQuery(sql);
query.setParameter(1, id);
query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.aliasToBean(CustomApproval.class));
return (CustomApproval) query.getSingleResult();
}
ps1:在Hibernate5.0版本以后采用?传参的索引值从1开始,在3、4版本是从0开始。
ps2:利用setResultTransformer的
Transformers.aliasToBean
可将sql的原生查询结果转换为实体对象;
Transformers.ALIAS_TO_ENTITY_MAP
将查询结果转为Map对象。
- 采用字段名
:字段名
方式
@PersistenceContext
private EntityManager entityManager;
@Override
public CustomApproval findApprovalById(Integer id) {
// TODO Auto-generated method stub
String sql = "select expiresAt,status,lastModifiedAt as lastUpdatedAt,userId,clientId,scope from oauth_approvals where id=:id";
Query query = entityManager.createNativeQuery(sql);
query.setParameter("id", id);
query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.aliasToBean(CustomApproval.class));
return (CustomApproval) query.getSingleResult();
}