List of usage examples for org.hibernate.criterion Projections distinct
public static Projection distinct(Projection projection)
From source file:ca.qc.cegepoutaouais.tge.pige.server.ManagementServiceImpl.java
License:Open Source License
@Override public List<Category> getCategories(Category parent, Boolean includeUnclassified) throws PigeException { logger.debug("Rcupration des catgories..."); Transaction tx = null;/* ww w . ja v a2 s . com*/ List<Category> categories = null; Session session = null; try { session = PigeHibernateUtil.openSession(); tx = session.beginTransaction(); Criteria criteria = session.createCriteria(Category.class); if (parent != null) { logger.debug("category != null: " + parent.getName()); criteria.add(Restrictions.eq(Category.PARENT_REF, parent)); } else { criteria.add(Restrictions.isNull(Category.PARENT_REF)); } criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); categories = (List) criteria.addOrder(Order.asc(Category.NAME_REF)).list(); if (categories != null) { for (Category c : categories) { Criteria itemCrit = session.createCriteria(Item.class); itemCrit.createCriteria(Item.CATEGORIES_REF) .add(Restrictions.like(Category.PATH_REF, c.getPath(), MatchMode.START)); itemCrit.setProjection(Projections.distinct(Projections.rowCount())); c.setItemCount((Integer) itemCrit.uniqueResult()); } } // la racine seulement. if (includeUnclassified && parent == null) { Category unclassified = new Category(); unclassified.setId(Category.UNCLASSIFIED_CATEGORY_ID); Criteria itemCrit = session.createCriteria(Item.class); itemCrit.add(Restrictions.sizeEq(Item.CATEGORIES_REF, 0)); itemCrit.setProjection(Projections.distinct(Projections.rowCount())); unclassified.setItemCount((Integer) itemCrit.uniqueResult()); categories.add(unclassified); } tx.commit(); logger.debug("Rcupration russie!"); } catch (Exception hex) { logger.error(hex); if (tx != null) { tx.rollback(); } } finally { if (session != null) { session.close(); } } return categories; }
From source file:com.amalto.core.storage.hibernate.StandardQueryHandler.java
License:Open Source License
@Override public StorageResults visit(Distinct distinct) { // Standard visit for the expression where distinct should be added distinct.getExpression().accept(this); // Wraps the last projection into a 'distinct' statement // Note: Hibernate does not provide projection editing functions... have to work around that with a new // projection list. ProjectionList newProjectionList = Projections.projectionList(); int i = 0;//from ww w. ja v a 2 s .c o m for (; i < projectionList.getLength() - 1; i++) { newProjectionList.add(projectionList.getProjection(i)); } newProjectionList.add(Projections.distinct(projectionList.getProjection(i))); projectionList = newProjectionList; return null; }
From source file:com.amalto.core.storage.hibernate.StandardQueryHandler.java
License:Open Source License
protected Criteria createCriteria(Select select) { List<ComplexTypeMetadata> selectedTypes = select.getTypes(); if (selectedTypes.isEmpty()) { throw new IllegalArgumentException("Select clause is expected to select at least one entity type."); //$NON-NLS-1$ }//from w ww . j a v a 2 s .c om mainType = selectedTypes.get(0); String mainClassName = ClassCreator.getClassName(mainType.getName()); criteria = session.createCriteria(mainClassName, mainType.getName()); if (!select.forUpdate()) { criteria.setReadOnly(true); // We are reading data, turns on ready only mode. } // Handle JOIN (if any) List<Join> joins = select.getJoins(); for (Join join : joins) { join.accept(this); } // If select is not a projection, selecting root type is enough, otherwise add projection for selected fields. if (select.isProjection()) { boolean toDistinct = true; projectionList = Projections.projectionList(); { List<TypedExpression> queryFields = select.getSelectedFields(); boolean isCountQuery = false; boolean hasGroupSize = false; for (Expression selectedField : queryFields) { if (selectedField instanceof GroupSize) { hasGroupSize = true; } selectedField.accept(this); if (selectedField instanceof Alias) { Alias alias = (Alias) selectedField; if (alias.getTypedExpression() instanceof Count) { isCountQuery = true; } if (alias.getTypedExpression() instanceof Distinct) { toDistinct = false; } } } // TMDM-9502/TMDM-10395, If selected fields including "GroupSize", besides GROUP BY "x_talend_task_id" // NOT ORACLE DB, should GROUP BY "All Key Fields" // ORACLE DB, need to GROUP BY "All Selected Fields" if (hasGroupSize) { projectionList = optimizeProjectionList(mainType, projectionList); } if (isCountQuery && queryFields.size() > 1) { Projection projection = projectionList.getProjection(projectionList.getLength() - 1); projectionList = Projections.projectionList(); projectionList.add(projection); TypedExpression countTypedExpression = selectedFields.get(queryFields.size() - 1); selectedFields.clear(); selectedFields.add(countTypedExpression); } } // for SELECT DISTINCT, ORDER BY expressions must appear in select list. Or it will throw exception in H2, postgres... for (OrderBy current : select.getOrderBy()) { if ((current.getExpression() instanceof Field && !select.getSelectedFields().contains(current.getExpression())) || current.getExpression() instanceof Type || current.getExpression() instanceof Alias) { toDistinct = false; break; } } if (select.getOrderBy().size() > 0 && toDistinct) { criteria.setProjection(Projections.distinct(projectionList)); } else { criteria.setProjection(projectionList); } } else { // TMDM-5388: Hibernate sometimes returns duplicate results (like for User stored in System storage), this // line avoids this situation. criteria.setResultTransformer(DistinctRootEntityResultTransformer.INSTANCE); } // Make projection read only in case code tries to modify it later (see code that handles condition). projectionList = ReadOnlyProjectionList.makeReadOnly(projectionList); // Handle condition (if there's any condition to handle). Condition condition = select.getCondition(); if (condition != null) { condition.accept(this); } // Order by for (OrderBy current : select.getOrderBy()) { if (current.getExpression() instanceof Count) { int limit = select.getPaging().getLimit(); if (limit > 0) { RDBMSDataSource dataSource = (RDBMSDataSource) storage.getDataSource(); if (dataSource.getDialectName() == RDBMSDataSource.DataSourceDialect.DB2 || dataSource.getDialectName() == RDBMSDataSource.DataSourceDialect.SQL_SERVER) { LOGGER.error("The query is not supported by DB2 and SQLSERVER Database."); //$NON-NLS-1$ throw new UnsupportedQueryException( "The query is not supported by DB2 and SQLSERVER Database."); //$NON-NLS-1$ } } } current.accept(this); } return criteria; }
From source file:com.ar.dev.tierra.api.dao.impl.ProductoDAOImpl.java
@SuppressWarnings("unchecked") @Override/*from ww w .j a v a 2s . c o m*/ public List<Producto> getAll() { Criteria criteria = getSession().createCriteria(Producto.class); ProjectionList projList = Projections.projectionList(); projList.add(Projections.property("idProducto"), "idProducto"); projList.add(Projections.property("marcas"), "marcas"); projList.add(Projections.property("descripcion"), "descripcion"); projList.add(Projections.property("colorProducto"), "colorProducto"); projList.add(Projections.property("cantidadTotal"), "cantidadTotal"); projList.add(Projections.property("talla"), "talla"); criteria.add(Restrictions.eq("estadoProducto", true)); criteria.addOrder(Order.desc("idProducto")); criteria.setProjection(Projections.distinct(projList)); criteria.setResultTransformer(Transformers.aliasToBean(Producto.class)); List<Producto> list = criteria.list(); return list; }
From source file:com.ar.dev.tierra.api.dao.impl.UsuariosDAOImpl.java
@SuppressWarnings("unchecked") @Override/*from w w w.j av a 2 s.com*/ public List<Usuarios> allUsuarios() { Criteria criteria = getSession().createCriteria(Usuarios.class); criteria.addOrder(Order.asc("idUsuario")); ProjectionList projList = Projections.projectionList(); projList.add(Projections.property("idUsuario"), "idUsuario"); projList.add(Projections.property("roles"), "roles"); projList.add(Projections.property("nombre"), "nombre"); projList.add(Projections.property("apellido"), "apellido"); projList.add(Projections.property("dni"), "dni"); projList.add(Projections.property("telefono"), "telefono"); projList.add(Projections.property("email"), "email"); projList.add(Projections.property("fechaNacimiento"), "fechaNacimiento"); projList.add(Projections.property("domicilio"), "domicilio"); projList.add(Projections.property("estado"), "estado"); projList.add(Projections.property("ultimaConexion"), "ultimaConexion"); projList.add(Projections.property("usuarioSucursal"), "usuarioSucursal"); criteria.setProjection(Projections.distinct(projList)); criteria.setResultTransformer(Transformers.aliasToBean(Usuarios.class)); List<Usuarios> us = criteria.list(); return us; }
From source file:com.ateam.hibernate.HibernateDAOImpl.java
public List<Questions> listSkills() throws DataAccessException, java.sql.SQLException { Questions obj = null;//from w w w. jav a 2s. c o m DetachedCriteria critfive = DetachedCriteria.forClass(Questions.class); critfive.setProjection(Projections.distinct(Projections.property("skillId"))); List objs = getHibernateTemplate().findByCriteria(critfive); return objs; }
From source file:com.bluexml.side.Framework.alfresco.jbpm.CustomJBPMEngine.java
License:Open Source License
/** * Construct a JBPM Hibernate query based on the Task Query provided * /* w ww. j a v a2s . c o m*/ * @param session * @param query * @return jbpm hiberate query criteria */ private Criteria createTaskQueryCriteria(Session session, WorkflowTaskQuery query) { Criteria task = session.createCriteria(TaskInstance.class); // task id if (query.getTaskId() != null) { task.add(Restrictions.eq("id", getJbpmId(query.getTaskId()))); } // task state if (query.getTaskState() != null) { WorkflowTaskState state = query.getTaskState(); if (state == WorkflowTaskState.IN_PROGRESS) { task.add(Restrictions.eq("isOpen", true)); task.add(Restrictions.isNull("end")); } else if (state == WorkflowTaskState.COMPLETED) { task.add(Restrictions.eq("isOpen", false)); task.add(Restrictions.isNotNull("end")); } } // task name if (query.getTaskName() != null) { task.add(Restrictions.eq("name", query.getTaskName().toPrefixString(namespaceService))); } // task actor if (query.getActorId() != null) { task.add(Restrictions.eq("actorId", query.getActorId())); } // task custom properties if (query.getTaskCustomProps() != null) { Map<QName, Object> props = query.getTaskCustomProps(); if (props.size() > 0) { Criteria variables = task.createCriteria("variableInstances"); Disjunction values = Restrictions.disjunction(); for (Map.Entry<QName, Object> prop : props.entrySet()) { Conjunction value = Restrictions.conjunction(); value.add(Restrictions.eq("name", factory.mapQNameToName(prop.getKey()))); value.add(Restrictions.eq("value", prop.getValue().toString())); values.add(value); } variables.add(values); } } // process criteria Criteria process = createProcessCriteria(task, query); // process custom properties if (query.getProcessCustomProps() != null) { // TODO: Due to Hibernate bug // http://opensource.atlassian.com/projects/hibernate/browse/HHH-957 // it's not possible to perform a sub-select with the criteria api. // For now issue a // secondary query and create an IN clause. Map<QName, Object> props = query.getProcessCustomProps(); if (props.size() > 0) { // create criteria for process variables Criteria variables = session.createCriteria(VariableInstance.class); variables.setProjection(Projections.distinct(Property.forName("processInstance"))); Disjunction values = Restrictions.disjunction(); for (Map.Entry<QName, Object> prop : props.entrySet()) { Conjunction value = Restrictions.conjunction(); value.add(Restrictions.eq("name", factory.mapQNameToName(prop.getKey()))); value.add(Restrictions.eq("value", prop.getValue().toString())); values.add(value); } variables.add(values); // note: constrain process variables to same criteria as tasks createProcessCriteria(variables, query); Disjunction processIdCriteria = createProcessIdCriteria(variables); // constrain tasks by process list process = (process == null) ? task.createCriteria("processInstance") : process; process.add(processIdCriteria); } } // order by if (query.getOrderBy() != null) { WorkflowTaskQuery.OrderBy[] orderBy = query.getOrderBy(); for (WorkflowTaskQuery.OrderBy orderByPart : orderBy) { if (orderByPart == WorkflowTaskQuery.OrderBy.TaskActor_Asc) { task.addOrder(Order.asc("actorId")); } else if (orderByPart == WorkflowTaskQuery.OrderBy.TaskActor_Desc) { task.addOrder(Order.desc("actorId")); } else if (orderByPart == WorkflowTaskQuery.OrderBy.TaskCreated_Asc) { task.addOrder(Order.asc("create")); } else if (orderByPart == WorkflowTaskQuery.OrderBy.TaskCreated_Desc) { task.addOrder(Order.desc("create")); } else if (orderByPart == WorkflowTaskQuery.OrderBy.TaskDue_Asc) { task.addOrder(Order.asc("dueDate")); } else if (orderByPart == WorkflowTaskQuery.OrderBy.TaskDue_Desc) { task.addOrder(Order.desc("dueDate")); } else if (orderByPart == WorkflowTaskQuery.OrderBy.TaskId_Asc) { task.addOrder(Order.asc("id")); } else if (orderByPart == WorkflowTaskQuery.OrderBy.TaskId_Desc) { task.addOrder(Order.desc("id")); } else if (orderByPart == WorkflowTaskQuery.OrderBy.TaskName_Asc) { task.addOrder(Order.asc("name")); } else if (orderByPart == WorkflowTaskQuery.OrderBy.TaskName_Desc) { task.addOrder(Order.desc("name")); } else if (orderByPart == WorkflowTaskQuery.OrderBy.TaskState_Asc) { task.addOrder(Order.asc("end")); } else if (orderByPart == WorkflowTaskQuery.OrderBy.TaskState_Desc) { task.addOrder(Order.desc("end")); } } } // limit results if (query.getLimit() != -1) { task.setMaxResults(query.getLimit()); } return task; }
From source file:com.bookselling.dao.SellerInvoiceDaoImpl.java
private Object[] filterCriteria(SellerInvoiceFilterForm form, int first, int items, int id) { String keyword = form.getKeyword(); SellerInvoiceFilterType searchBy = form.getSearchBy(); Date fromDate = form.getFromDate(); Date toDate = form.getToDate(); Double fromPrice = form.getFromPrice(); Double toPrice = form.getToPrice(); SellerInvoiceOrderType orderBy = form.getOrderBy(); SortType sortType = form.getSortType(); Criteria criteria = getSession().createCriteria(SellerInvoice.class); criteria.createAlias("seller", "sl").createAlias("buyer", "bye").createAlias("bye.account", "acc"); if (keyword != null) { keyword = "%" + keyword + "%"; if (searchBy == SellerInvoiceFilterType.BUYER) criteria.add(Restrictions.like("acc.username", keyword)); else if (searchBy == SellerInvoiceFilterType.OWNER) { Name name = new Name(); name.setName(keyword);/*from w ww . java 2 s . co m*/ criteria.add(Restrictions.like("bye.name", name)); } else if (searchBy == SellerInvoiceFilterType.ADDRESS) { Address address = new Address(); address.setAddress(keyword); criteria.add(Restrictions.like("contact.address", address)); } else if (searchBy == SellerInvoiceFilterType.PHONE) { PhoneNumber phone = new PhoneNumber(); phone.setPhoneNumber(keyword); criteria.add(Restrictions.like("contact.phoneNumber", phone)); } } if (fromDate != null) criteria.add(Restrictions.ge("createdDate", fromDate)); if (toDate != null) criteria.add(Restrictions.le("createdDate", toDate)); if (fromPrice != null) criteria.add(Restrictions.ge("totalPrice", fromPrice)); if (toPrice != null) criteria.add(Restrictions.le("totalPrice", toPrice)); String propertyName = null; if (orderBy == SellerInvoiceOrderType.BUYER) propertyName = "acc.username"; else if (orderBy == SellerInvoiceOrderType.OWNER) propertyName = "bye.name"; else if (orderBy == SellerInvoiceOrderType.DATE) propertyName = "createdDate"; else if (orderBy == SellerInvoiceOrderType.PRICE) propertyName = "totalPrice"; if (id != -1) criteria.add(Restrictions.eq("sl.id", id)); //Ly s dng long rowCount = (long) criteria.setProjection(Projections.countDistinct("id")).uniqueResult(); //Ly id criteria.setProjection(null).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY) .setProjection(Projections.distinct(Projections.id())).setFirstResult(first).setMaxResults(items) .addOrder(sortType == SortType.ASC ? Order.asc(propertyName) : Order.desc(propertyName)); List<Integer> ids = new ArrayList<>(); for (Iterator<Integer> temp = criteria.list().iterator(); temp.hasNext();) ids.add(temp.next()); //Criteria ph Criteria subCriteria = getSession().createCriteria(SellerInvoice.class); subCriteria.createAlias("seller", "sl").createAlias("buyer", "bye").createAlias("bye.account", "acc") .add(Restrictions.in("id", ids.size() > 0 ? ids : Arrays.asList(-1))) .addOrder(sortType == SortType.ASC ? Order.asc(propertyName) : Order.desc(propertyName)); return new Object[] { subCriteria, rowCount }; }
From source file:com.bookselling.dao.SellingPostDaoImpl.java
private Object[] genericFilter(SellingPostFilterForm criteriaForm, int first, int items, int id) { Criteria criteria = getSession().createCriteria(SellingPost.class); //parse form//from www.j a va 2s . com SellingPostFilterForm form = criteriaForm; //get form data String keyword = form.getKeyword(); Double minPrice = form.getMinPrice(); Double maxPrice = form.getMaxPrice(); QuatityFilterType quatityStatus = form.getQuatityStatus(); SellingPostFilterType searchBy = form.getSearchBy(); SellingPostStatus sellingPostStatus[] = form.getSellingPostStatus(); Set<Subject> subjects = form.getSubjects(); Integer subjectIds[] = new Integer[subjects.size()]; Subject subjectsArray[] = subjects.toArray(new Subject[subjectIds.length]); for (int i = 0; i < subjects.size(); i++) subjectIds[i] = subjectsArray[i].getId(); //create criteria criteria.createAlias("purchasingSellingEntity", "bk").createAlias("bk.subjects", "sbj") .createAlias("bk.publisher", "pub").createAlias("seller", "sl").createAlias("sl.account", "acc"); //search by keyword if (keyword != null && !keyword.isEmpty()) { keyword = "%" + keyword.trim() + "%"; if (searchBy == SellingPostFilterType.HEADER) criteria.add(Restrictions.like("header", keyword)); else if (searchBy == SellingPostFilterType.NAME) { criteria.add(Restrictions.like("bk.name", keyword)); //product } else if (searchBy == SellingPostFilterType.PUBLISHER) { criteria.add(Restrictions.like("pub.name", keyword)); } } //search with price range criteria.add(Restrictions.between("bk.sellingPrice", minPrice == null ? 0 : minPrice, maxPrice == null ? Integer.MAX_VALUE : maxPrice)); //search with quatity status if (quatityStatus == QuatityFilterType.AVAILABLE) criteria.add(Restrictions.gt("bk.quatity", 0)); else if (quatityStatus == QuatityFilterType.OUTOFSTOCK) criteria.add(Restrictions.eq("bk.quatity", 0)); //search with selling post status if (sellingPostStatus.length != 0) criteria.add(Restrictions.in("status", sellingPostStatus)); //search with subjects if (subjectIds.length != 0) criteria.add(Restrictions.in("sbj.id", subjectIds)); //get data from form SortType sortType = form.getSortType(); SellingPostOrderType sortByProperty = form.getSortByProperty(); //Set up criteria String propertyName = null; if (sortByProperty == SellingPostOrderType.HEADER) propertyName = "header"; else if (sortByProperty == SellingPostOrderType.NAME) propertyName = "bk.name"; else if (sortByProperty == SellingPostOrderType.PUBLISHER) propertyName = "pub.name"; else if (sortByProperty == SellingPostOrderType.CREATEDDATE) propertyName = "createdDate"; else if (sortByProperty == SellingPostOrderType.PRICE) propertyName = "bk.sellingPrice"; if (id != -1) criteria.add(Restrictions.eq("sl.id", id)); //Ly s dng long rowCount = (long) criteria.setProjection(Projections.countDistinct("id")).uniqueResult(); //Ly id criteria.setProjection(null).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY) .setProjection(Projections.distinct(Projections.id())).setFirstResult(first).setMaxResults(items) .addOrder(sortType == SortType.ASC ? Order.asc(propertyName) : Order.desc(propertyName)); List<Integer> ids = new ArrayList<>(); for (Iterator<Integer> temp = criteria.list().iterator(); temp.hasNext();) ids.add(temp.next()); //Criteria ph Criteria subCriteria = getSession().createCriteria(SellingPost.class); subCriteria.createAlias("purchasingSellingEntity", "bk").createAlias("bk.subjects", "sbj") .createAlias("bk.publisher", "pub").createAlias("seller", "sl").createAlias("sl.account", "acc") .add(Restrictions.in("id", ids.size() > 0 ? ids : Arrays.asList(-1))) .addOrder(sortType == SortType.ASC ? Order.asc(propertyName) : Order.desc(propertyName)); return new Object[] { subCriteria, rowCount }; }
From source file:com.bookselling.dao.SellingPostDaoImpl.java
@Override public PaginationData<SellingPost> getConfirmedPost(int first, int items) { SQLQuery sqlQuery = getSession().createSQLQuery(""); Criteria criteria = getSession().createCriteria(SellingPost.class) .add(Restrictions.eq("status", SellingPostStatus.CONFIRM)); //Ly s dng//from www. java2 s .c o m long rowCount = (long) criteria.setProjection(Projections.countDistinct("id")).uniqueResult(); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY) .setProjection(Projections.distinct(Projections.id())).addOrder(Order.desc("id")) .setFirstResult(first).setMaxResults(items); List<Integer> ids = new ArrayList<>(); for (Iterator<Integer> temp = criteria.list().iterator(); temp.hasNext();) ids.add(temp.next()); //Criteria ph Criteria subCriteria = getSession().createCriteria(SellingPost.class); subCriteria.createAlias("purchasingSellingEntity", "bk").createAlias("bk.subjects", "sbj") .createAlias("bk.publisher", "pub").createAlias("seller", "sl").createAlias("sl.account", "acc") .add(Restrictions.in("id", ids.size() > 0 ? ids : Arrays.asList(-1))).addOrder(Order.desc("id")); Set<SellingPost> posts = new HashSet(subCriteria.list()); HibernateInitSupport.setCls(SellingPost.class); for (SellingPost post : posts) HibernateInitSupport.initDomain(post); PaginationData paginationData = new PaginationData(rowCount, items, first, posts); return paginationData; }