List of usage examples for org.hibernate.criterion Projections distinct
public static Projection distinct(Projection projection)
From source file:ro.cs.om.model.dao.impl.DaoDepartmentImpl.java
License:Open Source License
/** * Searches for Departments after criterion from searchOrganisationBean. * * @author alu/*from ww w. j a v a2 s.c o m*/ * @author dan.damian */ public List<Department> getFromSearch(SearchDepartmentBean searchDepartmentBean, boolean isDeleteAction) throws ParseException { logger.debug("getFromSearch - START"); /*Once a Projection is being set to a Detached Criteria object, it cannot be removed anymore, so two identical DetachedCriteria objects must be created: -dcCount ( on which the projection is being set )used to retrieve the number of distinct results which is set when the request didn't come from the pagination area and needed further more to set the current page after a delete action; -dc used to retrieve the result set after the current page has been set in case of a delete action */ // set search criterion DetachedCriteria dc = DetachedCriteria.forEntityName(IModelConstant.departmentAllEntity); DetachedCriteria dcCount = DetachedCriteria.forEntityName(IModelConstant.departmentAllEntity); dc.createAlias("manager", "manager", Criteria.LEFT_JOIN); dcCount.createAlias("manager", "manager", Criteria.LEFT_JOIN); if (Tools.getInstance().stringNotEmpty(searchDepartmentBean.getName())) { dc.add(Restrictions.ilike("name", "%".concat(searchDepartmentBean.getName()).concat("%"))); dcCount.add(Restrictions.ilike("name", "%".concat(searchDepartmentBean.getName()).concat("%"))); logger.debug("name: " + searchDepartmentBean.getName()); } if (searchDepartmentBean.getOrganisationId() != -1) { dc.add(Restrictions.eq("organisation.organisationId", searchDepartmentBean.getOrganisationId())); dcCount.add(Restrictions.eq("organisation.organisationId", searchDepartmentBean.getOrganisationId())); logger.debug("Organisation Id: " + searchDepartmentBean.getOrganisationId()); } if (searchDepartmentBean.getManagerFirstName() != null && !"".equals(searchDepartmentBean.getManagerFirstName())) { dc.add(Restrictions.eq("manager.firstName", searchDepartmentBean.getManagerFirstName())); dcCount.add(Restrictions.eq("manager.firstName", searchDepartmentBean.getManagerFirstName())); logger.debug("Manager first name: ".concat(searchDepartmentBean.getManagerFirstName())); } if (searchDepartmentBean.getManagerLastName() != null && !"".equals(searchDepartmentBean.getManagerLastName())) { dc.add(Restrictions.eq("manager.lastName", searchDepartmentBean.getManagerLastName())); dcCount.add(Restrictions.eq("manager.lastName", searchDepartmentBean.getManagerLastName())); logger.debug("Manager last name: ".concat(searchDepartmentBean.getManagerLastName())); } if (Tools.getInstance().stringNotEmpty(searchDepartmentBean.getParentDepartmentName())) { dc.createCriteria("parentDepartment").add(Restrictions.ilike("name", "%".concat(searchDepartmentBean.getParentDepartmentName()).concat("%"))); dcCount.createCriteria("parentDepartment").add(Restrictions.ilike("name", "%".concat(searchDepartmentBean.getParentDepartmentName()).concat("%"))); logger.debug("Parent Department Name: " + searchDepartmentBean.getParentDepartmentName()); } if (searchDepartmentBean.getParentDepartmentId() != -1) { dc.add(Restrictions.eq("parentDepartment.departmentId", searchDepartmentBean.getParentDepartmentId())); dcCount.add( Restrictions.eq("parentDepartment.departmentId", searchDepartmentBean.getParentDepartmentId())); logger.debug("Parent Department Id: " + searchDepartmentBean.getParentDepartmentId()); } dc.add(Restrictions.eq("status", IConstant.NOM_DEPARTMENT_ACTIVE)); dcCount.add(Restrictions.eq("status", IConstant.NOM_DEPARTMENT_ACTIVE)); // check if I have to order the results if (searchDepartmentBean.getSortParam() != null && !"".equals(searchDepartmentBean.getSortParam())) { // if I have to, check if I have to order them ascending or descending if (searchDepartmentBean.getSortDirection() == -1) { // ascending dc.addOrder(Order.asc(searchDepartmentBean.getSortParam())); } else { // descending dc.addOrder(Order.desc(searchDepartmentBean.getSortParam())); } } // if the request didn't come from the pagination area, // it means that I have to set the number of result and pages if (isDeleteAction || searchDepartmentBean.getNbrOfResults() == -1) { boolean isSearch = false; if (searchDepartmentBean.getNbrOfResults() == -1) { isSearch = true; } // set the countDistinct restriction dcCount.setProjection(Projections.distinct(Projections.countDistinct("departmentId"))); int nbrOfResults = ((Integer) getHibernateTemplate().findByCriteria(dcCount, 0, 0).get(0)).intValue(); searchDepartmentBean.setNbrOfResults(nbrOfResults); logger.debug("NbrOfResults " + searchDepartmentBean.getNbrOfResults()); logger.debug("----> searchOrganisationBean.getResults " + searchDepartmentBean.getResultsPerPage()); // get the number of pages if (nbrOfResults % searchDepartmentBean.getResultsPerPage() == 0) { searchDepartmentBean.setNbrOfPages(nbrOfResults / searchDepartmentBean.getResultsPerPage()); } else { searchDepartmentBean.setNbrOfPages(nbrOfResults / searchDepartmentBean.getResultsPerPage() + 1); } // after a department is deleted, the same page has to be displayed; //only when all the departments from last page are deleted, the previous page will be shown if (isDeleteAction && (searchDepartmentBean.getCurrentPage() > searchDepartmentBean.getNbrOfPages())) { searchDepartmentBean.setCurrentPage(searchDepartmentBean.getNbrOfPages()); } else if (isSearch) { searchDepartmentBean.setCurrentPage(1); } } List<Department> res = getHibernateTemplate().findByCriteria(dc, (searchDepartmentBean.getCurrentPage() - 1) * searchDepartmentBean.getResultsPerPage(), searchDepartmentBean.getResultsPerPage()); logger.debug("Res " + res.size()); logger.debug("getFromSearch - END - results size : ".concat(String.valueOf(res.size()))); return res; }
From source file:ro.cs.om.model.dao.impl.DaoOOOImpl.java
License:Open Source License
/** * Returns a list of persons that figure as replacements in at least one OOO profile * Receives as param a list of persons ids to look for * @author coni/*from w w w. ja va 2 s . c om*/ * * @param personReplacementId * @return */ public List<Person> getOOOPersonReplacementsFromIds(Integer[] personReplacementId) { logger.debug("getByPersonReplacementID - START"); DetachedCriteria dc = DetachedCriteria.forEntityName(IModelConstant.oooAllEntity); dc.createCriteria("personReplacement").add(Restrictions.in("personId", personReplacementId)); dc.setProjection(Projections.distinct(Projections.property("personReplacement"))); List<Person> list = getHibernateTemplate().findByCriteria(dc); logger.debug("getByPersonReplacementID - END"); return list; }
From source file:ro.cs.om.model.dao.impl.DaoPersonImpl.java
License:Open Source License
/** * Return a list with all the Persons from the given Organization and Module and all the persons from organization * //from ww w . jav a 2s . c o m * @author mitziuro * * @param organizationId * @param moduleId * @return */ public Entry<List<Integer>, List<Person>> getPersonsIdsByOrganizationIdAndModuleId(int organizationId, int moduleId) { logger.debug("getPersonsIdsByOrganizationIdAndModuleId START: organizationId = " .concat(String.valueOf(organizationId).concat(" moduleId = ").concat(String.valueOf(moduleId)))); List<Integer> persons = null; List<Person> allPersons = null; DetachedCriteria dc = DetachedCriteria.forEntityName(IModelConstant.personForListingEntity); //we search for organisation id dc.createCriteria("depts").setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY) .add(Restrictions.eq("organisationId", new Integer(organizationId))); dc.add(Restrictions.ne("status", IConstant.NOM_PERSON_STATUS_DELETED)); //we search allPersons = getHibernateTemplate().findByCriteria(dc); DetachedCriteria dcp = DetachedCriteria.forEntityName(IModelConstant.personForListingEntity); //we search for organisation id dcp.createCriteria("depts").add(Restrictions.eq("organisationId", new Integer(organizationId))); dcp.add(Restrictions.ne("status", IConstant.NOM_PERSON_STATUS_DELETED)); //distinct results dcp.setProjection(Projections .distinct(Projections.projectionList().add(Projections.property("personId"), "personId"))); //we search for module id dcp.createCriteria("roles").add(Restrictions.eq("moduleId", new Integer(moduleId))); //we search persons = getHibernateTemplate().findByCriteria(dcp); logger.debug("getPersonsIdsByOrganizationIdAndModuleId END: size = " .concat(persons != null ? String.valueOf(allPersons.size()) : "null")); return new SimpleEntry(persons, allPersons); }
From source file:ro.cs.om.model.dao.impl.DaoPersonImpl.java
License:Open Source License
/** * Return a list with all the deactivated Persons from the given Organization and Module and all the persons from organization * /*ww w . j av a 2 s . c om*/ * @author liviu * * @param organizationId * @param moduleId * @return */ public Entry<List<Integer>, List<Person>> getDeletedPersonsIdsByOrganizationIdAndModuleId(int organizationId, int moduleId) { logger.debug("getDeletedPersonsIdsByOrganizationIdAndModuleId START: organizationId = " .concat(String.valueOf(organizationId).concat(" moduleId = ").concat(String.valueOf(moduleId)))); List<Integer> persons = null; List<Person> allPersons = null; DetachedCriteria dc = DetachedCriteria.forEntityName(IModelConstant.personForListingEntity); //we search for organisation id dc.createCriteria("depts").add(Restrictions.eq("organisationId", new Integer(organizationId))); dc.add(Restrictions.eq("status", IConstant.NOM_PERSON_STATUS_DELETED)); //we search allPersons = getHibernateTemplate().findByCriteria(dc); //we search for module id dc.createCriteria("roles").add(Restrictions.eq("moduleId", new Integer(moduleId))); //distinct results dc.setProjection(Projections .distinct(Projections.projectionList().add(Projections.property("personId"), "personId"))); //we search persons = getHibernateTemplate().findByCriteria(dc); logger.debug("getDeletedPersonsIdsByOrganizationIdAndModuleId END: size = " .concat(persons != null ? String.valueOf(persons.size()) : "null")); return new SimpleEntry(persons, allPersons); }
From source file:ro.cs.ts.model.dao.impl.DaoNotificationImpl.java
License:Open Source License
public List<Notification> getNotificationsFromSearch(SearchNotificationBean searchNotificationBean, boolean isDeleteAction) { logger.debug("getNotificationsFromSearch - START "); /*Once a Projection is being set to a Detached Criteria object, it cannot be removed anymore, so two identical DetachedCriteria objects must be created: /*from w w w. j ava 2 s . c o m*/ -dcCount ( on which the projection is being set )used to retrieve the number of distinct results which is set when the request didn't come from the pagination area and needed further more to set the current page after a delete action; -dc used to retrieve the result set after the current page has been set in case of a delete action */ // set search criterion DetachedCriteria dc = DetachedCriteria.forEntityName(IModelConstant.notificationEntity); DetachedCriteria dcCount = DetachedCriteria.forEntityName(IModelConstant.notificationEntity); dc.add(Restrictions.eq("receiverId", searchNotificationBean.getReceiverId())); dcCount.add(Restrictions.eq("receiverId", searchNotificationBean.getReceiverId())); if (searchNotificationBean.getStartDate() != null) { dc.add(Expression.ge("issuedDate", searchNotificationBean.getStartDate())); dcCount.add(Expression.ge("issuedDate", searchNotificationBean.getStartDate())); } if (searchNotificationBean.getEndDate() != null) { dc.add(Expression.le("issuedDate", searchNotificationBean.getEndDate())); dcCount.add(Expression.le("issuedDate", searchNotificationBean.getEndDate())); } if (searchNotificationBean.getMessage() != null && !"".equals(searchNotificationBean.getMessage())) { dc.add(Restrictions.ilike("message", "%".concat(searchNotificationBean.getMessage()).concat("%"))); dcCount.add(Restrictions.ilike("message", "%".concat(searchNotificationBean.getMessage()).concat("%"))); } // check if I have to order the results if (searchNotificationBean.getSortParam() != null && !"".equals(searchNotificationBean.getSortParam())) { // if I have to, check if I have to order them ascending or descending if (searchNotificationBean.getSortDirection() == -1) { // ascending dc.addOrder(Order.asc(searchNotificationBean.getSortParam())); } else { // descending dc.addOrder(Order.desc(searchNotificationBean.getSortParam())); } } // if the request didn't come from the pagination area, // it means that I have to set the number of results and pages if (isDeleteAction || searchNotificationBean.getNbrOfResults() == -1) { boolean isSearch = false; if (searchNotificationBean.getNbrOfResults() == -1) { isSearch = true; } // set the countDistinct restriction dcCount.setProjection(Projections.distinct(Projections.countDistinct(IModelConstant.notificationId))); int nbrOfResults = ((Integer) getHibernateTemplate().findByCriteria(dcCount, 0, 0).get(0)).intValue(); searchNotificationBean.setNbrOfResults(nbrOfResults); logger.debug("NbrOfResults " + searchNotificationBean.getNbrOfResults()); logger.debug("----> searchOrganisationBean.getResults " + searchNotificationBean.getResultsPerPage()); // get the number of pages if (nbrOfResults % searchNotificationBean.getResultsPerPage() == 0) { searchNotificationBean.setNbrOfPages(nbrOfResults / searchNotificationBean.getResultsPerPage()); } else { searchNotificationBean.setNbrOfPages(nbrOfResults / searchNotificationBean.getResultsPerPage() + 1); } // after a notification is deleted, the same page has to be displayed; // only when all the notifications from last page are deleted, the previous page will be shown if (isDeleteAction && (searchNotificationBean.getCurrentPage() > searchNotificationBean.getNbrOfPages())) { searchNotificationBean.setCurrentPage(searchNotificationBean.getNbrOfPages()); } else if (isSearch) { searchNotificationBean.setCurrentPage(1); } } List<Notification> res = getHibernateTemplate().findByCriteria(dc, Long.valueOf( (searchNotificationBean.getCurrentPage() - 1) * searchNotificationBean.getResultsPerPage()) .intValue(), Long.valueOf(searchNotificationBean.getResultsPerPage()).intValue()); if (res != null) { logger.debug("results size : ".concat(String.valueOf(res.size()))); } else { logger.debug("results size: 0"); } logger.debug("getNotificationsFromSearch - END"); return res; }
From source file:ru.trett.cis.DAO.DeviceModelDAOImpl.java
License:Open Source License
@SuppressWarnings("unchecked") public List<String> findBrandByType(String deviceType) { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(DeviceModel.class); criteria.createAlias("deviceType", "dt"); criteria.createAlias("deviceBrand", "db"); criteria.setProjection(Projections.distinct(Projections.property("db.brand"))); return criteria.add(Restrictions.eq("dt.type", deviceType).ignoreCase()).list(); }
From source file:sk.cagani.stuba.bpbp.serverApp.DatabaseConnector.java
public void writeDetailedStopsToFile() { FileOutputStream fos = null;/*from ww w . j a v a 2 s .c o m*/ try { Map<String, Object> jwConfig = new HashMap<>(); jwConfig.put(JsonGenerator.PRETTY_PRINTING, true); fos = new FileOutputStream("/home/debian/allDetailedStops.txt"); JsonWriter jw = Json.createWriterFactory(jwConfig).createWriter(fos, Charset.forName("UTF-8")); Session session = getSession(); Transaction tx = session.beginTransaction(); JsonArrayBuilder stopsJAB = Json.createArrayBuilder(); List<StopData> stopDataList = new ArrayList<>(); List<GtfsStops> stopsList = session.createCriteria(GtfsStops.class).addOrder(Order.asc("name")).list(); for (GtfsStops stop : stopsList) { StopData data = null; data = new StopData(); data.stop = stop; List<GtfsRoutes> routeList = session.createCriteria(GtfsStopTimes.class, "stopTime") .createAlias("stopTime.gtfsTrips", "trip").createAlias("trip.gtfsRoutes", "route") .add(Restrictions.eq("gtfsStops", stop)).addOrder(Order.asc("route.shortName")) .setProjection(Projections.distinct(Projections.projectionList() .add(Projections.property("route.shortName"), "shortName"))) .setResultTransformer(Transformers.aliasToBean(GtfsRoutes.class)).list(); data.setRouteList(routeList); stopDataList.add(data); } for (StopData sD : stopDataList) { //System.out.println(sD.getStop().getName()); StringBuilder vehicles = null; Collections.sort(sD.getRouteList(), new CustomComparator()); for (GtfsRoutes route : sD.getRouteList()) { if (vehicles == null) { vehicles = new StringBuilder(); vehicles.append(route.getShortName()); } else { vehicles.append(", " + route.getShortName()); } } if (vehicles == null) { vehicles = new StringBuilder(); vehicles.append("neobsluhovan"); } JsonObjectBuilder stopJOB = Json.createObjectBuilder(); stopJOB.add(sD.getStop().getId().getClass().getSimpleName(), sD.getStop().getId().getId()); stopJOB.add("name", sD.getStop().getName()); stopJOB.add("lat", sD.getStop().getLat()); stopJOB.add("lon", sD.getStop().getLon()); stopJOB.add("vehicles", vehicles.toString()); stopsJAB.add(stopJOB); } JsonObjectBuilder stopsJOB = Json.createObjectBuilder(); stopsJOB.add("stops", stopsJAB); JsonObject stopsJO = stopsJOB.build(); System.out.println(stopsJO.toString()); jw.writeObject(stopsJO); tx.commit(); //closes transaction session.close(); } catch (FileNotFoundException ex) { Logger.getLogger(DatabaseConnector.class.getName()).log(Level.SEVERE, null, ex); } finally { try { fos.close(); } catch (IOException ex) { Logger.getLogger(DatabaseConnector.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:sk.cagani.stuba.bpbp.serverApp.DatabaseConnector.java
public void writeStopsToFile() { FileOutputStream fos = null;/*from www.j ava2 s. co m*/ try { Map<String, Object> jwConfig = new HashMap<>(); jwConfig.put(JsonGenerator.PRETTY_PRINTING, true); fos = new FileOutputStream("/home/debian/allStops.txt"); JsonWriter jw = Json.createWriterFactory(jwConfig).createWriter(fos, Charset.forName("UTF-8")); Session session = getSession(); Transaction tx = session.beginTransaction(); List<GtfsStops> stopsList = session.createCriteria(GtfsStops.class).addOrder(Order.asc("name")).list(); JsonArrayBuilder stopsJAB = Json.createArrayBuilder(); List<StopData> stopDataList = new ArrayList<>(); for (GtfsStops stop : stopsList) { boolean found = false; StopData data = null; for (StopData stopData : stopDataList) { if (stopData.getStop().getName().equals(stop.getName())) { data = stopData; if (stop.getId().getId().endsWith("1")) { data.stop = stop; } found = true; break; } } if (data == null) { data = new StopData(); data.stop = stop; } List<GtfsRoutes> routeList = session.createCriteria(GtfsStopTimes.class, "stopTime") .createAlias("stopTime.gtfsTrips", "trip").createAlias("trip.gtfsRoutes", "route") .add(Restrictions.eq("gtfsStops", stop)).addOrder(Order.asc("route.shortName")) .setProjection(Projections.distinct(Projections.projectionList() .add(Projections.property("route.shortName"), "shortName"))) .setResultTransformer(Transformers.aliasToBean(GtfsRoutes.class)).list(); if (data.getRouteList().isEmpty()) { data.setRouteList(routeList); } else { for (GtfsRoutes route : routeList) { boolean foundRoute = false; for (GtfsRoutes route2 : data.getRouteList()) { if (route2.getShortName().equals(route.getShortName())) { foundRoute = true; } } if (foundRoute == false) { data.getRouteList().add(route); } } } if (found == false) { stopDataList.add(data); } } for (StopData sD : stopDataList) { //System.out.println(sD.getStop().getName()); StringBuilder vehicles = null; Collections.sort(sD.getRouteList(), new CustomComparator()); for (GtfsRoutes route : sD.getRouteList()) { // logger.debug(route.getShortName()); if (vehicles == null) { vehicles = new StringBuilder(); vehicles.append(route.getShortName()); } else { vehicles.append(", " + route.getShortName()); } } if (vehicles == null) { vehicles = new StringBuilder(); vehicles.append("neobsluhovan"); } JsonObjectBuilder stopJOB = Json.createObjectBuilder(); stopJOB.add(sD.getStop().getId().getClass().getSimpleName(), sD.getStop().getId().getId()); stopJOB.add("name", sD.getStop().getName()); stopJOB.add("lat", sD.getStop().getLat()); stopJOB.add("lon", sD.getStop().getLon()); stopJOB.add("vehicles", vehicles.toString()); stopsJAB.add(stopJOB); } JsonObjectBuilder stopsJOB = Json.createObjectBuilder(); stopsJOB.add("stops", stopsJAB); JsonObject stopsJO = stopsJOB.build(); System.out.println(stopsJO.toString()); jw.writeObject(stopsJO); tx.commit(); //closes transaction session.close(); } catch (FileNotFoundException ex) { Logger.getLogger(DatabaseConnector.class.getName()).log(Level.SEVERE, null, ex); } finally { try { fos.close(); } catch (IOException ex) { Logger.getLogger(DatabaseConnector.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:test.eurocarbdb.dataaccess.core.SubQueryTest.java
License:Open Source License
public void canSimpleDetachedSubQuery() { super.setup(); //Criteria subcriteria = em.createQuery( GlycanSequence.class ).setMaxResults( 20 ); DetachedCriteria subcriteria = DetachedCriteria.forClass(GlycanSequence.class); DetachedCriteria criteria;/*from w w w . j ava 2 s. c o m*/ criteria = DetachedCriteria.forClass(GlycanSequence.class); // criteria.add( Restrictions.lt( "glycanSequenceId", 100)); DetachedCriteria bc_crit = criteria.createCriteria("glycanContexts"); //DetachedCriteria bc_crit = DetachedCriteria.forClass( GlycanSequenceContext.class ); //criteria.createCriteria("glycanContexts"); bc_crit.add(Restrictions.gt("glycanSequenceContextId", 0)); bc_crit.setProjection(Projections.property("glycanSequenceContextId")); criteria.add(Subqueries.propertyIn("glycanSequenceContextId", bc_crit)); criteria.setProjection(Projections.distinct(Projections.property("glycanSequenceId"))); subcriteria.add(Subqueries.propertyIn("glycanSequenceId", criteria)); //System.out.println(subcriteria.list().size()); //subcriteria.getExecutableCriteria(((HibernateEntityManager) em).getHibernateSession()).setMaxResults(20).list(); super.teardown(); }
From source file:test.eurocarbdb.dataaccess.core.SubQueryTest.java
License:Open Source License
public void canDetachedSubQuery() { super.setup(); String taxonomyName = "homo sapiens"; //Criteria subcriteria = em.createQuery( GlycanSequence.class ).setMaxResults( 20 ); DetachedCriteria subcriteria = DetachedCriteria.forClass(GlycanSequence.class); DetachedCriteria criteria;/*from w ww . ja va2 s . c om*/ criteria = DetachedCriteria.forClass(GlycanSequence.class); DetachedCriteria bc_criteria; DetachedCriteria tax_criteria; bc_criteria = criteria.createCriteria("glycanContexts").createCriteria("biologicalContext", "bc"); // add taxonomy criteria if (taxonomyName != null) { tax_criteria = bc_criteria.createCriteria("taxonomy", "taxa") .createCriteria("taxonomySupertypes", "supertax") .add(Restrictions.ilike("taxon", taxonomyName, MatchMode.EXACT)); } criteria.setProjection(Projections.distinct(Projections.property("glycanSequenceId"))); subcriteria.add(Subqueries.propertyIn("glycanSequenceId", criteria)); //System.out.println(subcriteria.list().size()); subcriteria.getExecutableCriteria(((HibernateEntityManager) em).getHibernateSession()).list(); super.teardown(); }