zoukankan      html  css  js  c++  java
  • 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();
    }
    
  • 相关阅读:
    Python内置函数(14)——delattr
    Python内置函数(13)——complex
    Python内置函数(12)——compile
    Python内置函数(11)——classmethod
    Python内置函数(10)——chr
    Python内置函数(9)——callable
    Python内置函数(8)——bytes
    Python内置函数(7)——bytearray
    Python内置函数(6)——bool
    Python内置函数(4)——ascii
  • 原文地址:https://www.cnblogs.com/gmhappy/p/13457035.html
Copyright © 2011-2022 走看看