List of usage examples for org.hibernate.query Query setFirstResult
@Override
Query<R> setFirstResult(int startPosition);
From source file:be.shad.tsqb.dao.TypeSafeQueryDaoImpl.java
License:Apache License
/** * {@inheritDoc}/*from w ww .j a v a 2 s . c o m*/ */ @Override public <T> QueryResult<T> doQuery(TypeSafeRootQuery tsqbQuery, HibernateQueryConfigurer configurer) { HqlQuery hqlQuery = tsqbQuery.toHqlQuery(); Session currentSession = sessionFactory.getCurrentSession(); Query<Object[]> query = currentSession.createQuery(hqlQuery.getHql(), Object[].class); int position = 0; CollectionNamedParameter chunkedParam = null; for (Object param : hqlQuery.getParams()) { if (param instanceof NamedParameter) { NamedParameter named = (NamedParameter) param; if (isChunkedParam(named)) { if (chunkedParam != null) { throw new IllegalStateException( String.format("More than one batched param [%s, %s] was used in query [%s].", chunkedParam.getName(), named.getName(), query.getQueryString())); } // remember batched param to bind iterate and bind chunks later: chunkedParam = (CollectionNamedParameter) named; } else if (named.getValue() instanceof Collection) { query.setParameterList(named.getName(), (Collection<?>) named.getValue()); } else { query.setParameter(named.getName(), named.getValue()); } } else { query.setParameter(position++, param); } } if (tsqbQuery.getFirstResult() >= 0) { query.setFirstResult(tsqbQuery.getFirstResult()); } if (tsqbQuery.getMaxResults() > 0) { query.setMaxResults(tsqbQuery.getMaxResults()); } List<T> results = null; if (configurer != null) { configurer.beforeQuery(currentSession); configurer.configureQuery(query); try { results = listAll(query, hqlQuery, chunkedParam); } finally { configurer.afterQuery(currentSession); } } else { results = listAll(query, hqlQuery, chunkedParam); } return new QueryResult<>(results); }
From source file:com.msf.jsavings.commons.dao.DetachedHqlQuery.java
License:Open Source License
protected Query<R> createQuery(final Session session) { final Query<R> q = session.createQuery(toString()); params.entrySet().forEach((entry) -> { q.setParameter(entry.getKey(), entry.getValue()); });/* www. j a v a 2s . c o m*/ return q.setFirstResult(firstResult).setMaxResults(maxResults); }
From source file:com.pfm.personalfinancemanagergrid.mainClasses.DataGridDataManager.java
private Query buildQuery(Session session, GridParamObject params, boolean maxResults) throws ParseException, InstantiationException, IllegalAccessException { String source = cache.getEntity(); List<ColumnRequestObject> columns = params.getColumns(); String order = source.charAt(0) + "." + cache.getColumns().get(params.getOrder().get(0).getColumn()).getColumnName() + " " + params.getOrder().get(0).getDir(); String where = this.buildWhereStatement(params, source.charAt(0)); if (!"".equals(where)) { where = "where " + where; }/*w ww .j a v a2 s .com*/ Integer iterate = 0; Query q = session .createQuery("From " + source + " " + source.charAt(0) + " " + where + " order by " + order); for (GridCacheTableWhereObject whereObj : cache.getWheres()) { replaceQueryParameters(q, whereObj.getColumnType(), whereObj.getColumnName(), whereObj.getWhereVal(), whereObj.getWhereType(), "w_" + iterate); iterate++; } Integer iter = 0; if (iter < params.getColumns().size()) { for (ColumnRequestObject column : params.getColumns()) { GridCacheColumnObject cachedColumn = cache.getColumns().get(iter); if (!cachedColumn.isOptionsColumn() && cachedColumn.isSearchableColumn()) { String columnName = cachedColumn.getColumnName(); String compareType = column.getFilter().getValue(); String columnType = cachedColumn.getType(); String searchVal = column.getSearch().getValue(); replaceQueryParameters(q, columnType, columnName, searchVal, compareType, "s_" + iter); } iter++; } } if (maxResults) { q.setMaxResults(params.getLength()); q.setFirstResult(params.getStart()); } return q; }
From source file:com.wso2telco.services.dep.sandbox.dao.hibernate.HibernateProvisioningDAO.java
License:Open Source License
public List<ProvisionAllService> getApplicableProvisionServices(String number, String username, int offset, int limit) throws Exception { Session session = getSession();//w w w . j av a 2 s .c om List<ProvisionAllService> applicableServiceList = new ArrayList<ProvisionAllService>(); try { StringBuilder hqlQueryBuilder = new StringBuilder(); hqlQueryBuilder.append("select pas "); hqlQueryBuilder .append("from ProvisionAllService pas,ProvisionMSISDNServicesMap pmsm,ManageNumber mn,User u "); hqlQueryBuilder.append("where u.userName = :userName "); hqlQueryBuilder.append("and u.id = mn.user.id "); hqlQueryBuilder.append("and mn.id = pmsm.msisdnId.id "); hqlQueryBuilder.append("and pmsm.servicesId.id = pas.id "); hqlQueryBuilder.append("and mn.Number = :number "); Query query = session.createQuery(hqlQueryBuilder.toString()); query.setParameter("userName", username); query.setParameter("number", number); if (offset > 0) { query.setFirstResult(offset); } if (limit > 0) { query.setMaxResults(limit); } applicableServiceList = (List<ProvisionAllService>) query.getResultList(); } catch (Exception ex) { LOG.error("###PROVISION### Error in getApplicableProvisionServices " + ex); throw ex; } return applicableServiceList; }
From source file:com.wso2telco.services.dep.sandbox.dao.hibernate.HibernateProvisioningDAO.java
License:Open Source License
public List<ListProvisionedDTO> getActiveProvisionedServices(String msisdn, String username, int offset, int limit) throws Exception { Session session = getSession();// w w w . java 2 s . co m List<ListProvisionedDTO> resultSet = null; StringBuilder hql = new StringBuilder(); hql.append(" SELECT"); hql.append( " services.serviceCode AS serviceCode,services.description AS description,prservice.createdDate AS createdDate,services.tag AS tag,services.value AS value"); hql.append(" FROM"); hql.append(" ManageNumber AS num,"); hql.append(" ProvisionMSISDNServicesMap AS map,"); hql.append(" ProvisionedServices AS prservice,"); hql.append(" Status AS stat,"); hql.append(" ProvisionAllService AS services,"); hql.append(" User AS user"); hql.append(" WHERE num.Number = :number"); hql.append(" AND user.userName= :username"); hql.append(" AND user.id = num.user.id"); hql.append(" AND user.id = services.user.id"); hql.append(" AND map.msisdnId.id = num.id"); hql.append(" AND map.id = prservice.msisdnServiceMap.id"); hql.append(" AND map.servicesId.id = services.id"); hql.append(" AND stat.id = prservice.status.id"); hql.append(" AND stat.code= :status"); try { Query query = session.createQuery(hql.toString()); query.setParameter("status", ProvisioningStatusCodes.PRV_PROVISION_SUCCESS.toString()); query.setParameter("number", msisdn); query.setParameter("username", username); if (offset > 0) { query.setFirstResult(offset); } if (limit > 0) { query.setMaxResults(limit); } resultSet = query.setResultTransformer(Transformers.aliasToBean(ListProvisionedDTO.class)) .getResultList(); } catch (Exception ex) { LOG.error("###PROVISION### Error in getActiveProvisionedServices " + ex); throw ex; } return resultSet; }
From source file:com.wso2telco.services.dep.sandbox.dao.hibernate.HibernateWalletDAO.java
License:Open Source License
@Override public List<AttributeValues> getTransactionValue(String endUserId, List<String> attribute, String tableName, Integer userId) throws Exception { Session session = getSession();//from ww w . j a v a 2 s. c o m List<AttributeValues> resultSet = null; StringBuilder hql = new StringBuilder(); hql.append("SELECT "); hql.append("val "); hql.append("FROM "); hql.append("AttributeValues AS val, "); hql.append("APIServiceCalls AS calls, "); hql.append("APITypes AS api, "); hql.append("AttributeDistribution AS dist, "); hql.append("Attributes AS att, "); hql.append("ManageNumber AS number "); hql.append("WHERE "); hql.append("api.id = calls.apiType.id "); hql.append("AND calls.apiServiceCallId = dist.serviceCall.apiServiceCallId "); hql.append("AND dist.distributionId = val.attributeDistribution.distributionId "); hql.append("AND att.attributeId = dist.attribute.attributeId "); hql.append("AND api.apiname =:apiName "); hql.append("AND val.tobject =:tableName "); hql.append("AND number.id = val.ownerdid "); hql.append("AND number.Number =:number "); hql.append("AND number.user.id =:userId "); hql.append("AND att.attributeName IN ( :attributeName)"); try { Query query = session.createQuery(hql.toString()); query.setParameter("apiName", RequestType.WALLET.toString().toLowerCase()); query.setParameter("number", endUserId); query.setParameter("tableName", tableName); query.setParameterList("attributeName", attribute); query.setParameter("userId", userId); query.setFirstResult(0); query.setMaxResults(20); resultSet = (List<AttributeValues>) query.getResultList(); } catch (NoResultException e) { return null; } catch (Exception ex) { LOG.error("###WALLET### Error in getListTransaction Service ", ex); throw ex; } return resultSet; }
From source file:dk.fambagge.recipes.db.Database.java
public static <T extends DomainObject> Set<T> queryAll(String hql, Class<T> type, int firstResult, int maxResults) { final Set<T> namedResult = new LinkedHashSet<>(); execute((session) -> {//from ww w.j av a 2s. c o m Query query = session.createQuery(hql); if (firstResult != -1) { query.setFirstResult(firstResult); } if (maxResults != -1) { query.setMaxResults(maxResults); } query.setCacheable(true); for (Object resultObj : query.list()) { namedResult.add((T) resultObj); } }); return namedResult; }
From source file:dk.fambagge.recipes.web.data.LazyCustomList.java
@SuppressWarnings("Duplicates") @Override/* w ww . ja v a2 s .co m*/ public List<T> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters) { List<T> results = new ArrayList<>(); filterMap = new HashMap<>(); if (filters != null) { filterMap.putAll(filters); } if (customFilter != null) { filterMap.put("name", customFilter); } Database.execute((session) -> { CriteriaBuilder builder = session.getCriteriaBuilder(); CriteriaQuery<Long> criteriaCount = builder.createQuery(Long.class); Root<T> rootCount = criteriaCount.from(domainClass); Predicate[] predicatesCount = new Predicate[filterMap.size()]; //Setup filters int i = 0; for (Entry<String, Object> entry : filterMap.entrySet()) { String filterField = entry.getKey(); String filterValue = entry.getValue().toString(); predicatesCount[i] = builder.like(builder.lower(rootCount.get(filterField)), "%" + filterValue.toLowerCase() + "%"); i++; } criteriaCount.select(builder.count(rootCount)); criteriaCount.where(predicatesCount); int count = session.createQuery(criteriaCount).uniqueResult().intValue(); this.setRowCount(count); CriteriaQuery<T> criteria = builder.createQuery(domainClass); Root<T> root = criteria.from(domainClass); Predicate[] predicates = new Predicate[filterMap.size()]; //Setup filters i = 0; for (Entry<String, Object> entry : filterMap.entrySet()) { String filterField = entry.getKey(); String filterValue = entry.getValue().toString(); predicates[i] = builder.like(builder.lower(root.get(filterField)), "%" + filterValue.toLowerCase() + "%"); i++; } criteria.select(root); criteria.where(predicates); String sortFieldFixed = sortField == null ? "name" : sortField; SortOrder sortOrderFixed = sortOrder == null ? SortOrder.ASCENDING : sortOrder; switch (sortOrderFixed) { case ASCENDING: criteria.orderBy(builder.asc(root.get(sortFieldFixed))); break; case DESCENDING: criteria.orderBy(builder.desc(root.get(sortFieldFixed))); break; } Query<T> query = session.createQuery(criteria); query.setFirstResult(first); query.setMaxResults(pageSize); results.addAll(query.getResultList()); }); return results; }
From source file:it.greenvulcano.gvesb.iam.repository.hibernate.UserRepositoryHibernate.java
License:Open Source License
public Set<User> find(Map<Parameter, Object> parameters, LinkedHashMap<Parameter, Order> order, int firstResult, int maxResult) { Set<User> result = new LinkedHashSet<>(); QueryHelper helper = buildQueryHelper(false, parameters, order); @SuppressWarnings("unchecked") Query<UserJPA> q = getSession().createQuery(helper.getQuery().toString()); helper.getParams().entrySet().forEach(p -> q.setParameter(p.getKey(), p.getValue())); q.setFirstResult(firstResult); q.setMaxResults(maxResult);//from w w w .j a v a2 s. c o m result.addAll(q.getResultList()); return result; }
From source file:org.kitodo.data.database.persistence.BaseDAO.java
License:Open Source License
/** * Retrieves BaseBean objects from database by given query. * * @param query//w w w . j a v a 2 s . c om * as String * @param parameters * for query * @param first * result * @param max * amount of results * @return list of beans objects */ @SuppressWarnings("unchecked") public List<T> getByQuery(String query, Map<String, Object> parameters, int first, int max) { try (Session session = HibernateUtil.getSession()) { Query q = session.createQuery(query); q.setFirstResult(first); q.setMaxResults(max); addParameters(q, parameters); return (List<T>) q.list(); } }