List of usage examples for org.hibernate.criterion Projections count
public static CountProjection count(String propertyName)
From source file:grails.orm.HibernateCriteriaBuilder.java
License:Apache License
/** * Adds a projection that allows the criteria to return the property count * * @param propertyName The name of the property * @param alias The alias to use// ww w . j av a 2 s .c o m */ public void count(String propertyName, String alias) { final CountProjection proj = Projections.count(calculatePropertyName(propertyName)); addProjectionToList(proj, alias); }
From source file:jp.go.nict.langrid.dao.hibernate.HibernateNewsDao.java
License:Open Source License
@Override public boolean isNewsExist(int newsId) throws DaoException { try {//from w w w.ja v a2 s .co m return ((Integer) getSession().createCriteria(News.class).add(Property.forName("id").eq(newsId)) .setProjection(Projections.count("id")).uniqueResult()) > 0; } catch (HibernateException e) { logAdditionalInfo(e); throw new DaoException(e); } }
From source file:jp.go.nict.langrid.dao.hibernate.HibernateUserDao.java
License:Open Source License
public boolean hasUserRole(final String userGridId, final String userId, final String role) throws DaoException { return transact(new DaoBlockR<Boolean>() { @Override// w w w . ja v a 2 s. c o m public Boolean execute(Session session) throws DaoException { int c = (Integer) session.createCriteria(UserRole.class).setProjection(Projections.count("userId")) .add(Property.forName("gridId").eq(userGridId)).add(Property.forName("userId").eq(userId)) .add(Property.forName("roleName").eq(role)).uniqueResult(); return c > 0; } }); }
From source file:Mob.MobLoadMonthlySales.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {//from w w w .j ava2s. c o m PrintWriter pw = resp.getWriter(); DataInputStream ds = new DataInputStream(req.getInputStream()); String dfr = ds.readUTF(); String dto = ds.readUTF(); String cat = ds.readUTF(); String pcd = ds.readUTF(); ds.close(); String datefrmarr[] = dfr.split(" "); String datetoarr[] = dto.split(" "); Session con = FactoryManager.getSessionFactory().openSession(); List<Object[]> list; Criteria cri = con.createCriteria(TransProd.class); SimpleDateFormat sdf = new SimpleDateFormat("MMM/dd/yyyy"); if (dfr != null && dto != null) { Criteria cri2 = cri.createCriteria("transaction"); if (!dfr.equals("")) { Date d = sdf.parse(datefrmarr[1] + "/" + datefrmarr[2] + "/" + datefrmarr[5]); cri2.add(Restrictions.ge("transDate", d)); } if (!dto.equals("")) { Date d = sdf.parse(datetoarr[1] + "/" + datetoarr[2] + "/" + datetoarr[5]); cri2.add(Restrictions.le("transDate", d)); } } cri.setProjection(Projections.projectionList().add(Projections.groupProperty("stock")) .add(Projections.count("qty"))); // cri.createAlias("stock", "s").add(Projections.groupProperty("s.batchid")); list = cri.list(); String out = ""; double subtot = 0.0; for (Object[] obj : list) { Stock stk = (Stock) obj[0]; long qty = (Long) obj[1]; if (!pcd.equals("All")) { if (stk.getProducts().getProdCode().equals(pcd)) { out += "Product Code : " + stk.getProducts().getProdCode(); out += " "; out += "Batch ID : " + stk.getBatchid(); out += " "; out += "Product Name : " + stk.getProducts().getBrand().getBrandName() + " " + stk.getProducts().getItmName(); out += " "; out += "Quantity : " + qty; out += " "; out += "Price : " + stk.getItmPrice(); out += " "; out += "Discount : " + stk.getDiscount(); out += " "; out += "Total : " + (stk.getItmPrice() - stk.getDiscount()) * qty; subtot += (stk.getItmPrice() - stk.getDiscount()) * qty; out += ","; } } else if (!cat.equals("0")) { if (stk.getProducts().getCategory().getIdcat().equals(Integer.parseInt(cat))) { out += "Product Code : " + stk.getProducts().getProdCode(); out += " "; out += "Batch ID : " + stk.getBatchid(); out += " "; out += "Product Name : " + stk.getProducts().getBrand().getBrandName() + " " + stk.getProducts().getItmName(); out += " "; out += "Quantity : " + qty; out += " "; out += "Price : " + stk.getItmPrice(); out += " "; out += "Discount : " + stk.getDiscount(); out += " "; out += "Total : " + (stk.getItmPrice() - stk.getDiscount()) * qty; subtot += (stk.getItmPrice() - stk.getDiscount()) * qty; out += ","; } } else { out += "Product Code : " + stk.getProducts().getProdCode(); out += " "; out += "Batch ID : " + stk.getBatchid(); out += " "; out += "Product Name : " + stk.getProducts().getBrand().getBrandName() + " " + stk.getProducts().getItmName(); out += " "; out += "Quantity : " + qty; out += " "; out += "Price : " + stk.getItmPrice(); out += " "; out += "Discount : " + stk.getDiscount(); out += " "; out += "Total : " + (stk.getItmPrice() - stk.getDiscount()) * qty; subtot += (stk.getItmPrice() - stk.getDiscount()) * qty; out += ","; } } out += "Sub Total : Rs." + subtot; out += ","; pw.print(out); } catch (Exception e) { e.printStackTrace(); } }
From source file:monasca.api.infrastructure.persistence.hibernate.AlarmSqlRepoImpl.java
License:Apache License
@Override public void deleteById(String tenantId, String id) { logger.trace(ORM_LOG_MARKER, "deleteById(...) entering"); Transaction tx = null;//from w w w.ja v a 2 s . c o m Session session = null; try { session = sessionFactory.openSession(); tx = session.beginTransaction(); final long result = (Long) session.createCriteria(AlarmDb.class, "a") .createAlias("alarmDefinition", "ad") .add(Restrictions.conjunction(Restrictions.eq("a.id", id), Restrictions.eq("ad.tenantId", tenantId), Restrictions.eqProperty("a.alarmDefinition.id", "ad.id"), Restrictions.isNull("ad.deletedAt"))) .setProjection(Projections.count("a.id")).setReadOnly(true).uniqueResult(); // This will throw an EntityNotFoundException if Alarm doesn't exist or has a different tenant // id if (result < 1) { throw new EntityNotFoundException("No alarm exists for %s", id); } // delete alarm session.getNamedQuery(AlarmDb.Queries.DELETE_BY_ID).setString("id", id).executeUpdate(); tx.commit(); tx = null; } catch (Exception e) { this.rollbackIfNotNull(tx); throw e; } finally { if (session != null) { session.close(); } } }
From source file:net.firejack.platform.api.registry.broker.ReadBaseBIReportDataBroker.java
License:Apache License
@Override protected ServiceResponse<BIReportData> perform(ServiceRequest<NamedValues> request) throws Exception { Long biReportUserId = (Long) request.getData().get("id"); String parentNodeValues = (String) request.getData().get("parentNodeValues"); String[] parentRowValues = WebUtils.deserializeJSON(parentNodeValues, String[].class); int depth = parentRowValues.length; ServiceResponse<BIReportData> response; ServiceResponse<BIReportUser> biReportUserResponse = OPFEngine.RegistryService .readBIReportUser(biReportUserId); if (biReportUserResponse.isSuccess()) { BIReportData biReport = new BIReportData(); BIReportUser biReportUser = biReportUserResponse.getItem(); List<BIReportUserField> biReportUserFields = biReportUser.getFields(); Map<Long, BIReportField> entityBIReportFieldMap = new HashMap<Long, BIReportField>(); for (BIReportField biReportField : biReportUser.getReport().getFields()) { if (biReportField.getField() == null) { entityBIReportFieldMap.put(biReportField.getEntity().getId(), biReportField); }/*from www .j ava 2 s . co m*/ } Integer columnIndex = 0; List<BIReportColumn> biReportColumns = new ArrayList<BIReportColumn>(); Map<BIReportField, BIReportLocation> groupedBIReportFields = new LinkedHashMap<BIReportField, BIReportLocation>(); Map<Integer, BIReportRow> verticalColumnsMapping = new HashMap<Integer, BIReportRow>(); List<BIReportUserField> verticalBIReportUserFields = getFieldsByLocation(biReportUserFields, BIReportLocation.VERTICAL); Entity previousEntity = null; for (int i = 0; i < verticalBIReportUserFields.size(); i++) { BIReportUserField biReportUserField = verticalBIReportUserFields.get(i); BIReportField biReportField = biReportUserField.getField(); Entity entity = biReportField.getEntity(); if (previousEntity == null || !previousEntity.getId().equals(entity.getId())) { String columnName = entity.getName(); BIReportField entityBIReportField = entityBIReportFieldMap.get(entity.getId()); if (entityBIReportField != null) { columnName = StringUtils.defaultIfEmpty(entityBIReportField.getDisplayName(), columnName); } BIReportColumn biReportColumn = new BIReportColumn(); biReportColumn.setName(columnName); biReportColumn.setType(BIReportLocation.VERTICAL); biReportColumn.setColumnIndex(columnIndex); biReportColumn.setExpanded(biReportUserField.isExpanded()); biReportColumn.setUnShift(i); biReportColumns.add(biReportColumn); columnIndex++; previousEntity = entity; } BIReportRow biReportRow = new BIReportRow(); biReportRow.setColumnIndex(biReportColumns.size() - 1); biReportRow.setExpanded(biReportUserField.isExpanded()); verticalColumnsMapping.put(i, biReportRow); groupedBIReportFields.put(biReportField, BIReportLocation.VERTICAL); } biReport.setCountOfLevels(verticalColumnsMapping.size()); List<BIReportUserField> horizontalBIReportUserFields = getFieldsByLocation(biReportUserFields, BIReportLocation.HORIZONTAL); Map<Entity, List<BIReportField>> entityBIReportFields = new LinkedHashMap<Entity, List<BIReportField>>(); for (BIReportUserField biReportUserField : horizontalBIReportUserFields) { BIReportField biReportField = biReportUserField.getField(); Entity entity = biReportField.getEntity(); List<BIReportField> biReportFields = entityBIReportFields.get(entity); if (biReportFields == null) { biReportFields = new ArrayList<BIReportField>(); entityBIReportFields.put(entity, biReportFields); } biReportFields.add(biReportField); groupedBIReportFields.put(biReportField, BIReportLocation.HORIZONTAL); } List<BIReportUserField> measureBIReportUserFields = getFieldsByLocation(biReportUserFields, BIReportLocation.MEASURE); for (BIReportUserField biReportUserField : measureBIReportUserFields) { BIReportField biReportField = biReportUserField.getField(); groupedBIReportFields.put(biReportField, BIReportLocation.MEASURE); } String biReportUserFilter = biReportUser.getFilter(); biReport.setFilter(biReportUserFilter); List<List<SearchQuery>> filterSearchQueries = WebUtils.deserializeJSON(biReportUserFilter, List.class, List.class, SearchQuery.class); BIReportUserField measureBIReportUserField = measureBIReportUserFields.get(0); BIReportField measureBIReportField = measureBIReportUserField.getField(); Entity factEntity = measureBIReportField.getEntity(); String factDomainClassName = FormattingUtils.classFormatting(factEntity.getName()); String factModelClassName = factEntity.getPath() + ".model." + factDomainClassName + "Model"; Class<?> factModelClass = Class.forName(factModelClassName); List<Object[]> globalList = null; for (Map.Entry<Entity, List<BIReportField>> entry : entityBIReportFields.entrySet()) { Entity entity = entry.getKey(); List<BIReportField> biReportFields = entry.getValue(); String domainClassName = FormattingUtils.classFormatting(entity.getName()); String modelClassName = entity.getPath() + ".model." + domainClassName + "Model"; String storeClassName = entity.getPath() + ".store.Basic" + domainClassName + "Store"; IAbstractStore store = OpenFlameSpringContext.getBean(storeClassName); List<List<SearchQuery>> columnSearchQueryList = new ArrayList<List<SearchQuery>>(); List<SortField> sortFields = new ArrayList<SortField>(); ProjectionList projectionList = Projections.projectionList(); for (BIReportField biReportField : biReportFields) { Field field = biReportField.getField(); String fieldName = FormattingUtils.fieldModelFormatting(field.getName()); projectionList.add(Projections.property(fieldName)); sortFields.add(new SortField(fieldName, SortOrder.ASC)); String fkDimFieldName = findDimFieldName(factModelClass, modelClassName); for (List<SearchQuery> searchQueries : filterSearchQueries) { List<SearchQuery> columnSearchQueries = new ArrayList<SearchQuery>(); for (SearchQuery searchQuery : searchQueries) { String searchField = searchQuery.getField(); String[] fieldNames = searchField.split("\\."); if (fieldNames.length == 2 && fieldNames[0].equals(fkDimFieldName)) { SearchQuery columnSearchQuery = new SearchQuery(fieldNames[1], searchQuery.getOperation(), searchQuery.getValue()); columnSearchQueries.add(columnSearchQuery); } } if (columnSearchQueries.isEmpty()) { SearchQuery alwaysTrueSearchQuery = new SearchQuery(); columnSearchQueries.add(alwaysTrueSearchQuery); } columnSearchQueryList.add(columnSearchQueries); } } Paging paging = new Paging(null, null, sortFields); List<Object[]> objectsList; if (biReportFields.size() > 1) { objectsList = store.advancedSearchWithProjection(columnSearchQueryList, Projections.distinct(projectionList), null, paging); } else { objectsList = new ArrayList<Object[]>(); List<Object> objectList = store.advancedSearchWithProjection(columnSearchQueryList, Projections.distinct(projectionList), null, paging); for (Object object : objectList) { objectsList.add(new Object[] { object }); } } if (globalList == null) { globalList = objectsList; } else { List<Object[]> mergedList = new ArrayList<Object[]>(); for (Object[] globalObjects : globalList) { for (Object[] objects : objectsList) { Object[] mergedObjects = ArrayUtils.addAll(globalObjects, objects); mergedList.add(mergedObjects); } } globalList = mergedList; } } List<BIReportField> measureBIReportFields = getFieldsByLocation(groupedBIReportFields, BIReportLocation.MEASURE); Map<ArrayKey, Integer> horizontalColumnMapping = generateHorizontalColumns(globalList, biReportColumns, measureBIReportFields, columnIndex); if (depth == 0) { biReport.setColumns(biReportColumns); } int countOfExpandedChildren = 1; int countOfVerticalColumns = verticalColumnsMapping.size(); for (int i = depth; i < countOfVerticalColumns; i++) { BIReportRow verticalBIReportRow = verticalColumnsMapping.get(i); if (verticalBIReportRow.isExpanded()) { countOfExpandedChildren++; } else { break; } } ProjectionList projectionList = Projections.projectionList(); List<SortField> sortFields = new ArrayList<SortField>(); Map<String, String> aliases = new HashMap<String, String>(); int positionOfLastExpandedColumns = depth + countOfExpandedChildren - 1; List<SearchQuery> childrenFilterSearchQueries = new ArrayList<SearchQuery>(); List<BIReportField> verticalBIReportFields = getFieldsByLocation(groupedBIReportFields, new BIReportLocation[] { BIReportLocation.VERTICAL }); for (int i = 0; i < verticalBIReportFields.size(); i++) { BIReportField biReportField = verticalBIReportFields.get(i); Entity dimEntity = biReportField.getEntity(); String dimDomainClassName = FormattingUtils.classFormatting(dimEntity.getName()); String dimModelClassName = dimEntity.getPath() + ".model." + dimDomainClassName + "Model"; String fkDimFieldName = findDimFieldName(factModelClass, dimModelClassName); aliases.put(fkDimFieldName, fkDimFieldName); Field field = biReportField.getField(); String fieldName = FormattingUtils.fieldModelFormatting(field.getName()); String aliasedFieldName = fkDimFieldName + "." + fieldName; projectionList.add(Projections.groupProperty(aliasedFieldName)); sortFields.add(new SortField(aliasedFieldName, SortOrder.ASC)); if (positionOfLastExpandedColumns >= i + 1) { if (depth >= i + 1) { SearchQuery searchQuery = new SearchQuery(); searchQuery.setField(aliasedFieldName); searchQuery.setOperation(QueryOperation.EQUALS); searchQuery.setValue(parentRowValues[i]); childrenFilterSearchQueries.add(searchQuery); } } else { break; } } if (filterSearchQueries.isEmpty()) { filterSearchQueries.add(childrenFilterSearchQueries); } else { for (List<SearchQuery> searchQueries : filterSearchQueries) { for (SearchQuery childrenFilterSearchQuery : childrenFilterSearchQueries) { searchQueries.add(childrenFilterSearchQuery); } } } List<BIReportField> horizontalBIReportFields = getFieldsByLocation(groupedBIReportFields, new BIReportLocation[] { BIReportLocation.HORIZONTAL }); for (BIReportField biReportField : horizontalBIReportFields) { Entity dimEntity = biReportField.getEntity(); String dimDomainClassName = FormattingUtils.classFormatting(dimEntity.getName()); String dimModelClassName = dimEntity.getPath() + ".model." + dimDomainClassName + "Model"; String fkDimFieldName = findDimFieldName(factModelClass, dimModelClassName); aliases.put(fkDimFieldName, fkDimFieldName); Field field = biReportField.getField(); String fieldName = FormattingUtils.fieldModelFormatting(field.getName()); String aliasedFieldName = fkDimFieldName + "." + fieldName; projectionList.add(Projections.groupProperty(aliasedFieldName)); sortFields.add(new SortField(aliasedFieldName, SortOrder.ASC)); } for (BIReportField biReportField : measureBIReportFields) { Field field = biReportField.getField(); String fieldName = FormattingUtils.fieldModelFormatting(field.getName()); projectionList.add(Projections.count(fieldName)); } String storeClassName = factEntity.getPath() + ".store.Basic" + factDomainClassName + "Store"; IAbstractStore store = OpenFlameSpringContext.getBean(storeClassName); List<Object[]> dataList = store.advancedSearchWithProjection(filterSearchQueries, Projections.distinct(projectionList), aliases, new Paging(null, null, sortFields)); int countOfHorizontalColumns = horizontalBIReportUserFields.size(); int countOfMeasureColumns = measureBIReportUserFields.size(); List<BIReportRow> biReportRows = generateRows(dataList, verticalColumnsMapping, horizontalColumnMapping, countOfVerticalColumns, countOfHorizontalColumns, countOfMeasureColumns, depth, countOfExpandedChildren); biReport.setRows(biReportRows); response = new ServiceResponse<BIReportData>(biReport, "BI Report data", true); } else { response = new ServiceResponse<BIReportData>( "Could not find user configuration of BIReport by ID: " + biReportUserId, false); } return response; }
From source file:net.firejack.platform.core.store.registry.PackageChangesStore.java
License:Apache License
@Transactional(readOnly = true) public Long countEntityChanges(final Long entityId) { return getHibernateTemplate().execute(new HibernateCallback<Long>() { public Long doInHibernate(Session session) throws HibernateException, SQLException { Criteria criteria = session.createCriteria(getClazz()); criteria.add(Restrictions.eq("entity.id", entityId)); criteria.setProjection(Projections.count("id")); return (Long) criteria.uniqueResult(); }/* ww w.ja v a 2s . com*/ }); }
From source file:net.longfalcon.newsj.persistence.hibernate.ConsoleInfoDAOImpl.java
License:Open Source License
@Override @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public Long countConsoleInfos() { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(ConsoleInfo.class); criteria.setProjection(Projections.count("id")); return (Long) criteria.uniqueResult(); }
From source file:net.longfalcon.newsj.persistence.hibernate.ReleaseCommentDAOImpl.java
License:Open Source License
@Override @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public Long countReleaseComments() { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(ReleaseComment.class); criteria.setProjection(Projections.count("id")); return (Long) criteria.uniqueResult(); }
From source file:net.longfalcon.newsj.persistence.hibernate.ReleaseDAOImpl.java
License:Open Source License
/** * * @return List of Object[] = {Category,long} *///from w ww . j ava 2 s . com @Override @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public List<Object[]> findRecentlyAddedReleaseCategories() { Date oneWeekAgo = DateTime.now().minusWeeks(1).toDate(); Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Release.class); criteria.add(Restrictions.ge("addDate", oneWeekAgo)); criteria.setProjection( Projections.projectionList().add(Projections.groupProperty("category").as("category")) .add(Projections.count("id").as("count"))); criteria.addOrder(Order.desc("count")); criteria.setMaxResults(10); return criteria.list(); }