Hibernate createQuery查询传递参数的两种方式

  • 采用问号?方式传参
@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();
}

posted on 2020-04-10 17:19  疯狂的小萝卜头  阅读(2079)  评论(0编辑  收藏  举报