Java Code Examples for javax.persistence.Query.unwrap()

The following are Jave code examples for showing how to use unwrap() of the javax.persistence.Query class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: tianti   File: CustomBaseSqlDaoImpl.java   Source Code and License Vote up 6 votes
@SuppressWarnings("unchecked")
public List<Map<String, Object>> querySqlObjects(String sql, Object params, Integer currentPage,Integer rowsInPage){
	Query qry = em.createNativeQuery(sql);
	SQLQuery s = qry.unwrap(SQLQuery.class);
	
	//设置参数
	if(params != null){
		if(params instanceof List){
			List<Object> paramList = (List<Object>) params;
			for(int i = 0, size = paramList.size(); i < size; i++){
				qry.setParameter(i+1, paramList.get(i));
			}
		}else if(params instanceof Map){
			Map<String, Object> paramMap = (Map<String, Object>) params;
			for(String key : paramMap.keySet()){
				qry.setParameter(key, paramMap.get(key));
			}
		}
	}
	
	if (currentPage != null && rowsInPage != null) {//判断是否有分页
		// 起始对象位置
		qry.setFirstResult(rowsInPage * (currentPage - 1));
		// 查询对象个数
		qry.setMaxResults(rowsInPage);
	}
	s.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
	List<Map<String, Object>> resultList=new ArrayList<Map<String, Object>>();
	try {
		resultList=s.list();
	} catch (Exception e) {
	}finally{
		em.close();
	}
	return resultList;
}
 
Example 2
Project: dev-courses   File: ToDoListDAO.java   Source Code and License Vote up 5 votes
public void updateTask(final ToDoList pToDoList) {
	
       final CriteriaBuilder lCriteriaBuilder = entityManager.getCriteriaBuilder();
       
       //Creation de la requête d'update
       final CriteriaUpdate<ToDoList> lCriteriaUpdate = lCriteriaBuilder.createCriteriaUpdate(ToDoList.class);
       final Root<ToDoList> lRoot = lCriteriaUpdate.from(ToDoList.class);
       final Path<ToDoList> lPath = lRoot.get("id");
       //On utilise la variable pToDoList transmise en parametre de la methode
       final Expression<Boolean> lExpression = lCriteriaBuilder.equal(lPath, pToDoList.getId());
       lCriteriaUpdate.where(lExpression);
       lCriteriaUpdate.set("libelle", pToDoList.getLibelle());
       
       final Query lQuery = entityManager.createQuery(lCriteriaUpdate);
       final int lRowCount = lQuery.executeUpdate();
       
       //Si la requête modifie un nombre d'occurrences différent de 1 > erreur
       //Sinon update fait.
       if (lRowCount != 1) {
           final org.hibernate.Query lHQuery = lQuery.unwrap(org.hibernate.Query.class);
           final String lSql = lHQuery.getQueryString();
           throw new RuntimeException("Nombre d'occurences (" + lRowCount + 
                   ") modifiés différent de 1 pour " + lSql);
       }
	
}
 
Example 3
Project: tianti   File: CustomBaseSqlDaoImpl.java   Source Code and License Vote up 5 votes
/**
 * 根据SQL语句查询分页
 * @param sql
 * @param currentPage
 * @param pageSize
 * @return
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public PageModel queryForPageBySql(String sql,Integer currentPage,Integer pageSize){
	PageModel page = new PageModel();
	Integer totalCount = 0;
	Integer totalPage = 0;
	
	//EntityManager em = this.emf.createEntityManager();
	Query qry = em.createNativeQuery(sql);
	Query qry2 = em.createNativeQuery(sql);
	SQLQuery s = qry.unwrap(SQLQuery.class);
	if (currentPage != null && pageSize != null) {//判断是否有分页
		// 起始对象位置
		qry.setFirstResult(pageSize * (currentPage - 1));
		// 查询对象个数
		qry.setMaxResults(pageSize);
	}
	s.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
	List<Map> resultList=new ArrayList<Map>();
	List list = qry2.getResultList();
	totalCount = (list == null ? 0 : list.size());
	if(totalCount % pageSize == 0){
		totalPage = totalCount/pageSize;
	}else{
		totalPage = totalCount/pageSize + 1;
	}
	try {
		resultList=s.list();
		page.setCurrentPage(currentPage);
		page.setPageSize(pageSize);
		page.setList(resultList);
		page.setTotalCount(totalCount);
		page.setTotalPage(totalPage);
	} catch (Exception e) {
		e.printStackTrace();
	}finally{
		em.close();
	}		
	return page;
}
 
Example 4
Project: xq_seckill_microservice   File: BasicRepositoryImpl.java   Source Code and License Vote up 5 votes
@Override
public Map queryForMap(String querySql, Object... params) {
    Query query = entityManager.createNativeQuery(querySql);
    SQLQuery nativeQuery = query.unwrap(SQLQuery.class);
    nativeQuery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
    if (params != null) {
        for (int i = 0; i < params.length; i++) {
            nativeQuery.setParameter(i, params[i]);
        }
    }
    return (Map) nativeQuery.uniqueResult();
}
 
Example 5
Project: xq_seckill_microservice   File: BasicRepositoryImpl.java   Source Code and License Vote up 5 votes
@Override
public List<Map> queryForMapList(String querySql, Object... params) {
    Query query = entityManager.createNativeQuery(querySql);
    SQLQuery nativeQuery = query.unwrap(SQLQuery.class);
    nativeQuery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
    if (params != null) {
        for (int i = 0; i < params.length; i++) {
            nativeQuery.setParameter(i, params[i]);
        }
    }
    return nativeQuery.list();
}
 
Example 6
Project: xq_seckill_microservice   File: BasicRepositoryImpl.java   Source Code and License Vote up 5 votes
@Override
public Object queryForObject(String querySql, Object... params) {
    Query query = entityManager.createNativeQuery(querySql);
    SQLQuery nativeQuery = query.unwrap(SQLQuery.class);
    if (params != null) {
        for (int i = 0; i < params.length; i++) {
            nativeQuery.setParameter(i, params[i]);
        }
    }
    return nativeQuery.uniqueResult();
}
 
Example 7
Project: xq_seckill_microservice   File: BasicRepositoryImpl.java   Source Code and License Vote up 5 votes
@Override
public List<Object> queryForObjectList(String querySql, Object... params) {
    Query query = entityManager.createQuery(querySql);
    SQLQuery nativeQuery = query.unwrap(SQLQuery.class);
    if (params != null) {
        for (int i = 0; i < params.length; i++) {
            nativeQuery.setParameter(i, params[i]);
        }
    }

    return nativeQuery.list();
}
 
Example 8
Project: xq_seckill_microservice   File: BasicRepositoryImpl.java   Source Code and License Vote up 5 votes
@Override
public int executeUpdateBySql(String executeSql, Object... params) {
    Query query = entityManager.createNativeQuery(executeSql);
    SQLQuery nativeQuery = query.unwrap(SQLQuery.class);
    if (params != null) {
        for (int i = 0; i < params.length; i++) {
            nativeQuery.setParameter(i, params[i]);
        }
    }

    return nativeQuery.executeUpdate();
}
 
Example 9
Project: tianti   File: CustomBaseSqlDaoImpl.java   Source Code and License Vote up 4 votes
@SuppressWarnings({ "rawtypes", "unchecked" })
public PageModel queryForPageBySql(String sql,Map<String,Object> params,Integer currentPage,Integer pageSize){
	PageModel page = new PageModel();
	Integer totalCount = 0;
	Integer totalPage = 0;
	
	Query qry = em.createNativeQuery(sql);
	Query qry2 = em.createNativeQuery(sql);
	
	for(Map.Entry<String,Object> entry: params.entrySet()){
		qry.setParameter(entry.getKey(), entry.getValue());
		qry2.setParameter(entry.getKey(), entry.getValue());
	}
	
	SQLQuery s = qry.unwrap(SQLQuery.class);
	if (currentPage != null && pageSize != null) {//判断是否有分页
		// 起始对象位置
		qry.setFirstResult(pageSize * (currentPage - 1));
		// 查询对象个数
		qry.setMaxResults(pageSize);
	}
	s.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
	List<Map> resultList=new ArrayList<Map>();
	List list = qry2.getResultList();
	totalCount = (list == null ? 0 : list.size());
	if(totalCount % pageSize == 0){
		totalPage = totalCount/pageSize;
	}else{
		totalPage = totalCount/pageSize + 1;
	}
	try {
		resultList=s.list();
		page.setCurrentPage(currentPage);
		page.setPageSize(pageSize);
		page.setList(resultList);
		page.setTotalCount(totalCount);
		page.setTotalPage(totalPage);
	} catch (Exception e) {
		e.printStackTrace();
	}finally{
		em.close();
	}		
	return page;
}
 
Example 10
Project: OperatieBRP   File: CustomSimpleMaxedJpaRepository.java   Source Code and License Vote up 4 votes
@Override
protected TypedQuery<Long> getCountQuery(final Specification<T> spec) {
    final CriteriaBuilder builder = em.getCriteriaBuilder();
    final CriteriaQuery<T> criteria = builder.createQuery(getDomainClass());
    final Root<T> root = applySpecificationToQueryCriteria(spec, criteria);
    criteria.select(root);
    final TypedQuery<T> query = em.createQuery(criteria);

    
    final AbstractQueryImpl hibernateQuery = query.unwrap(AbstractQueryImpl.class);
    @SuppressWarnings("unchecked")
    final Map<String, TypedValue> pNamedParameters = (Map<String, TypedValue>) getField(hibernateQuery, AbstractQueryImpl.class, "namedParameters");

    final String hql = hibernateQuery.getQueryString();

    final ASTQueryTranslatorFactory queryTranslatorFactory = new ASTQueryTranslatorFactory();
    final SessionImplementor hibernateSession = em.unwrap(SessionImplementor.class);
    final QueryTranslator queryTranslator =
            queryTranslatorFactory.createQueryTranslator("", hql, Collections.emptyMap(), hibernateSession.getFactory(), null);
    queryTranslator.compile(Collections.emptyMap(), false);
    final String sql = queryTranslator.getSQLString();
    final ParameterTranslations paramTranslations = queryTranslator.getParameterTranslations();

    final String countSql = String.format("select count(*) from (%s limit %d) as sqry", sql, maximumRecords + 1);

    final Query nativeQuery = em.createNativeQuery(countSql);

    
    final AbstractQueryImpl resultQuery = nativeQuery.unwrap(AbstractQueryImpl.class);

    if (pNamedParameters != null) {
        for (final Entry<String, TypedValue> entry : pNamedParameters.entrySet()) {
            for (final int index : paramTranslations.getNamedParameterSqlLocations(entry.getKey())) {

                resultQuery.setParameter(index, entry.getValue().getValue(), entry.getValue().getType());
            }
        }
    }

    return new CustomCountQueryWrapper(nativeQuery);
}