org.hibernate.criterion.DetachedCriteria Java Examples

The following examples show how to use org.hibernate.criterion.DetachedCriteria. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OlingoManager.java    From DataHubSystem with GNU Affero General Public License v3.0 8 votes vote down vote up
public List<Product> getProducts(User user, String uuid,
      FilterExpression filter_expr, OrderByExpression order_expr, int skip,
      int top) throws ExceptionVisitExpression, ODataApplicationException
{
   ProductSQLVisitor expV = new ProductSQLVisitor();
   Object visit_result = null;

   if (filter_expr != null)
   {
      visit_result = filter_expr.accept(expV);
   }
   if (order_expr != null)
   {
      visit_result = order_expr.accept(expV);
   }

   return productService.getProducts((DetachedCriteria) visit_result, uuid,
         skip, top);
}
 
Example #2
Source File: HibernateTemplate.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public List<?> findByCriteria(final DetachedCriteria criteria, final int firstResult, final int maxResults)
		throws DataAccessException {

	Assert.notNull(criteria, "DetachedCriteria must not be null");
	return executeWithNativeSession(new HibernateCallback<List<?>>() {
		@Override
		public List<?> doInHibernate(Session session) throws HibernateException {
			Criteria executableCriteria = criteria.getExecutableCriteria(session);
			prepareCriteria(executableCriteria);
			if (firstResult >= 0) {
				executableCriteria.setFirstResult(firstResult);
			}
			if (maxResults > 0) {
				executableCriteria.setMaxResults(maxResults);
			}
			return executableCriteria.list();
		}
	});
}
 
Example #3
Source File: ProductService.java    From DataHubSystem with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Odata dedicated Services
 */
@Transactional(readOnly = true)
@Cacheable (value = "product_count", key = "{#criteria, #uuid}")
public int countProducts (DetachedCriteria criteria, String uuid)
{
   if (criteria == null)
   {
      criteria = DetachedCriteria.forClass (Product.class);
   }

   // count only processed products
   criteria.add (Restrictions.eq ("processed", true));

   if (uuid != null)
   {
      List<Long> product_ids = collectionService.getProductIds (uuid);
      criteria.add (Restrictions.in ("id", product_ids));
   }
   criteria.setProjection (Projections.rowCount ());
   return productDao.count (criteria);
}
 
Example #4
Source File: SignupMeetingDaoImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Override
public List<String> getAllCategories(String siteId) throws DataAccessException {
	DetachedCriteria criteria = DetachedCriteria.forClass(
			SignupMeeting.class).setProjection(Projections.distinct(Projections.projectionList()
				    	    .add(Projections.property("category"), "category") )).setResultTransformer(
			Criteria.DISTINCT_ROOT_ENTITY)				
			.addOrder(Order.asc("category")).createCriteria("signupSites")
			.add(Restrictions.eq("siteId", siteId));
	
	List<String> categorys = (List<String>) getHibernateTemplate().findByCriteria(criteria);
	
	if(categorys !=null && !categorys.isEmpty()){
		return categorys;
	}
	
	return null;
}
 
Example #5
Source File: CriteriaQuery.java    From jeecg with Apache License 2.0 6 votes vote down vote up
public CriteriaQuery(Class entityClass,DataTables dataTables) {
	this.curPage = dataTables.getDisplayStart();
	String[] fieldstring=dataTables.getsColumns().split(",");

	this.detachedCriteria = DetachedCriteria.forClass(entityClass);
	//this.detachedCriteria = DetachedCriteriaUtil.createDetachedCriteria(entityClass, "start", "_table",fieldstring);

	
	this.field=dataTables.getsColumns();
	this.entityClass=entityClass;
	this.dataTables=dataTables;
	this.pageSize=dataTables.getDisplayLength();
	this.map = new HashMap<String, Object>();

	this.ordermap = new LinkedHashMap<String, Object>();

	addJqCriteria(dataTables);
}
 
Example #6
Source File: CriteriaQuery.java    From jeecg with Apache License 2.0 6 votes vote down vote up
public CriteriaQuery(Class<?> entityClass,DataGrid dg) {
	this.curPage = dg.getPage();
	//String[] fieldstring=dg.getField().split(",");
	//this.detachedCriteria = DetachedCriteriaUtil
	//.createDetachedCriteria(c, "start", "_table",fieldstring);
	this.detachedCriteria = DetachedCriteria.forClass(entityClass);
	//Criteria criteria = null;

	this.field=dg.getField();
	this.entityClass=entityClass;
	this.dataGrid=dg;
	this.pageSize=dg.getRows();
	this.map = new HashMap<String, Object>();

	this.ordermap = new LinkedHashMap<String, Object>();

}
 
Example #7
Source File: HibernateTemplate.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public List<?> findByCriteria(final DetachedCriteria criteria, final int firstResult, final int maxResults)
		throws DataAccessException {

	Assert.notNull(criteria, "DetachedCriteria must not be null");
	return nonNull(executeWithNativeSession((HibernateCallback<List<?>>) session -> {
		Criteria executableCriteria = criteria.getExecutableCriteria(session);
		prepareCriteria(executableCriteria);
		if (firstResult >= 0) {
			executableCriteria.setFirstResult(firstResult);
		}
		if (maxResults > 0) {
			executableCriteria.setMaxResults(maxResults);
		}
		return executableCriteria.list();
	}));
}
 
Example #8
Source File: ECRFFieldValueDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 6 votes vote down vote up
private org.hibernate.Criteria[] createEcrfFieldCriteria(Long probandListEntryId, Long ecrfId) {
	org.hibernate.Criteria ecrfFieldCriteria = this.getSession().createCriteria(ECRFField.class, ServiceUtil.ECRF_FIELD_VALUE_DAO_ECRF_FIELD_ALIAS);
	ecrfFieldCriteria.add(Restrictions.eq("ecrf.id", ecrfId.longValue()));
	org.hibernate.Criteria ecrfFieldValueCriteria = ecrfFieldCriteria.createCriteria("fieldValues", ServiceUtil.ECRF_FIELD_VALUE_DAO_ECRF_FIELD_VALUE_ALIAS,
			CriteriaSpecification.LEFT_JOIN,
			Restrictions.eq(ServiceUtil.ECRF_FIELD_VALUE_DAO_ECRF_FIELD_VALUE_ALIAS + ".listEntry.id", probandListEntryId.longValue()));
	// correlated - slow:
	DetachedCriteria subQuery = createEcrfFieldValueDetachedCriteriaMaxId(ecrfFieldValueCriteria, ecrfFieldCriteria, null, probandListEntryId, null);
	subQuery.add(Restrictions.or(Restrictions.isNull("index"),
			Restrictions.eqProperty("index", ServiceUtil.ECRF_FIELD_VALUE_DAO_ECRF_FIELD_VALUE_ALIAS + ".index")));
	ecrfFieldValueCriteria.add(Restrictions.or(
			Restrictions.isNull("listEntry"),
			Restrictions.and(
					Restrictions.eq("listEntry.id", probandListEntryId.longValue()),
					Subqueries.propertyIn("id", subQuery))));
	return new org.hibernate.Criteria[] { ecrfFieldCriteria, ecrfFieldValueCriteria };
}
 
Example #9
Source File: K8sApiStatusDaoImpl.java    From kardio with Apache License 2.0 6 votes vote down vote up
@Override
public long getCurrentNumberOfApis(int envId,String componentIdsStrg) throws ParseException {
	
	List<Integer> comIdList = DaoUtil.convertCSVToList(componentIdsStrg);
	
	Session session = sessionFactory.openSession();
	DetachedCriteria subMaxDate = DetachedCriteria.forClass(K8sApiStatusEntity.class);
	subMaxDate.setProjection(Projections.max("statusDate"));
	Criteria crtCurrenrApi = session.createCriteria(K8sApiStatusEntity.class);
	crtCurrenrApi.add(Property.forName("statusDate").eq(subMaxDate));
	DaoUtil.addEnvironmentToCriteria(envId, comIdList, crtCurrenrApi);
	crtCurrenrApi.setProjection(Projections.sum("totalApi"));
	long currentNumberOfApi = (long) (crtCurrenrApi.uniqueResult() == null ? (long)0 : crtCurrenrApi.uniqueResult());
	session.close();
	return currentNumberOfApi;
}
 
Example #10
Source File: HomePageController.java    From TinyMooc with Apache License 2.0 6 votes vote down vote up
@RequestMapping("goPersonalTeam.htm")
public ModelAndView goPersonalTeam(HttpServletRequest request) {
    String userId = request.getParameter("userId");
    User user1 = userService.findById(User.class, userId);
    DetachedCriteria dCriteria = DetachedCriteria.forClass(UserTeam.class);
    dCriteria.add(Restrictions.eq("user", user1));

    List<UserTeam> userTeam = userService.queryAllOfCondition(UserTeam.class, dCriteria);
    DetachedCriteria dCriteria2 = DetachedCriteria.forClass(Discuss.class);
    dCriteria2.add(Restrictions.eq("user", user1));
    List<Discuss> discussList = userService.queryAllOfCondition(Discuss.class, dCriteria2);

    request.setAttribute("user1", user1);
    request.setAttribute("userTeam", userTeam);
    request.setAttribute("discussList", discussList);
    return new ModelAndView("/userPage/userGroup");
}
 
Example #11
Source File: BaseDaoImpl.java    From csustRepo with MIT License 6 votes vote down vote up
/**
	 * 通过Criteria来查询
	 * @param criterion
	 * @param order
	 * @return 查询实体对象的结果列表
	 */
	@Transactional
	public List<T> cquery(Collection<Criterion> criterions,
			Collection<Order> orders) {
//		Session session=getSessionBeginTx();
//		
//		Criteria criteria = criteriaQuery(session,criterions, orders);
//		
//		List<T> list= criteria.list();
//		//提交事务
//		closeCommitTx(session);
		DetachedCriteria dc=DetachedCriteria.forClass(entityClass);
		if(criterions!=null){
			for (Criterion criterion : criterions) {
				dc.add(criterion);
			}
		}
		if(orders!=null){
			for (Order order : orders) {
				dc.addOrder(order);
			}
		}
		
		return getHibernateTemplate().findByCriteria(dc);
	}
 
Example #12
Source File: SimplePageToolDaoImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public List<SimplePage> getTopLevelPages(final String siteId) {
    // set of all top level pages, actually the items pointing to them                                                                       
	try {
		List<SitePage> sitePages = siteService.getSite(siteId).getOrderedPages();
		if (sitePages.isEmpty()) {
			return null;
		}

		final List<String> sitePageIds = sitePages.stream().map(sp -> sp.getId()).collect(Collectors.toList());

		DetachedCriteria d = DetachedCriteria.forClass(SimplePage.class);
		d.add(Restrictions.in("toolId", sitePageIds));
		d.add(Restrictions.isNull("parent"));

		List<SimplePage> lessonsPages = (List<SimplePage>) getHibernateTemplate().findByCriteria(d);

		return lessonsPages;

	} catch (IdUnusedException e) {
		log.warn("Could not find site: " + siteId, e);
		return null;
	}

}
 
Example #13
Source File: SimplePageToolDaoImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public List<SimplePage> getSitePages(String siteId) {
    DetachedCriteria d = DetachedCriteria.forClass(SimplePage.class).add(Restrictions.eq("siteId", siteId))
	    .add(Restrictions.disjunction()
			    .add(Restrictions.isNull("owner"))
			    .add(Restrictions.eq("owned", true))
	    );

	List<SimplePage> l = (List<SimplePage>) getHibernateTemplate().findByCriteria(d);

	if (l != null && l.size() > 0) {
	    return l;
	} else {
	    return null;
	}
}
 
Example #14
Source File: BaseServiceImpl.java    From TinyMooc with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Transactional(readOnly = true)
public <T> List<T> queryAllOfCondition(Class<T> clazz, DetachedCriteria dCriteria) {
    Criteria criteria = dCriteria.getExecutableCriteria(getCurrentSession());
    List<T> list = criteria.list();
    return list;
}
 
Example #15
Source File: PasswordDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected Collection<Password> handleFindExpiring(Date today,
		Long departmentId, AuthenticationType authMethod, VariablePeriod reminderPeriod,
		Long reminderPeriodDays, Boolean notify, boolean includeAlreadyPassed, PSFVO psf) throws Exception {
	org.hibernate.Criteria passwordCriteria = createPasswordCriteria("password0");
	SubCriteriaMap criteriaMap = new SubCriteriaMap(Password.class, passwordCriteria);
	if (departmentId != null) {
		criteriaMap.createCriteria("user").add(Restrictions.eq("department.id", departmentId.longValue()));
	}
	if (authMethod != null) {
		criteriaMap.createCriteria("user").add(Restrictions.eq("authMethod", authMethod));
	}
	DetachedCriteria subQuery = DetachedCriteria.forClass(PasswordImpl.class, "password1"); // IMPL!!!!
	subQuery.add(Restrictions.eqProperty("password1.user", "password0.user"));
	subQuery.setProjection(Projections.max("id"));
	passwordCriteria.add(Subqueries.propertyEq("id", subQuery));
	passwordCriteria.add(Restrictions.eq("expires", true)); // performance only...
	if (notify != null) {
		passwordCriteria.add(Restrictions.eq("prolongable", notify.booleanValue())); // performance only...
	}
	if (psf != null) {
		PSFVO sorterFilter = new PSFVO();
		sorterFilter.setFilters(psf.getFilters());
		sorterFilter.setSortField(psf.getSortField());
		sorterFilter.setSortOrder(psf.getSortOrder());
		CriteriaUtil.applyPSFVO(criteriaMap, sorterFilter);
	}
	ArrayList<Password> resultSet = CriteriaUtil.listExpirations(passwordCriteria, today, notify, includeAlreadyPassed, null, null, reminderPeriod, reminderPeriodDays);
	return CriteriaUtil.applyPVO(resultSet, psf, false); // no dupes by default
}
 
Example #16
Source File: ProductDao.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
public Product getProductByIdentifier (String identifier)
{
   DetachedCriteria criteria = DetachedCriteria.forClass (Product.class);
   criteria.add (Restrictions.eq ("identifier", identifier));
   criteria.add (Restrictions.eq ("processed", true));
   return uniqueResult (criteria);
}
 
Example #17
Source File: ProbandDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected Collection<Proband> handleFindByMoneyTransferNoParticipation(Long trialId,
		PaymentMethod method, String costType, Boolean paid, boolean total,
		Boolean person, PSFVO psf)
		throws Exception {
	org.hibernate.Criteria probandCriteria = createProbandCriteria("proband0");
	if (person != null) {
		probandCriteria.add(Restrictions.eq("person", person.booleanValue()));
	}
	SubCriteriaMap criteriaMap = new SubCriteriaMap(Proband.class, probandCriteria);
	Criteria moneyTransferCriteria = criteriaMap.createCriteria("moneyTransfers");
	moneyTransferCriteria.add(Restrictions.eq("trial.id", trialId.longValue()));
	if (method != null) {
		moneyTransferCriteria.add(Restrictions.eq("method", method));
	}
	if (paid != null) {
		moneyTransferCriteria.add(Restrictions.eq("paid", paid.booleanValue()));
	}
	CategoryCriterion.apply(moneyTransferCriteria, new CategoryCriterion(costType, "costType", MatchMode.EXACT, EmptyPrefixModes.ALL_ROWS));
	DetachedCriteria subQuery = DetachedCriteria.forClass(ProbandListEntryImpl.class, "probandListEntry"); // IMPL!!!!
	subQuery.setProjection(Projections.rowCount());
	subQuery.add(Restrictions.eqProperty("proband.id", "proband0.id"));
	subQuery.add(Restrictions.eq("trial.id", trialId.longValue()));
	if (!total) {
		subQuery.createCriteria("lastStatus", CriteriaSpecification.INNER_JOIN).createCriteria("status", CriteriaSpecification.INNER_JOIN)
				.add(Restrictions.eq("count", true));
	}
	probandCriteria.add(Subqueries.eq(0l, subQuery));
	return CriteriaUtil.listDistinctRootPSFVO(criteriaMap, psf, this);
}
 
Example #18
Source File: ECRFFieldValueDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static void applyEcrfFieldValueMaxIdSubCriteria(org.hibernate.Criteria ecrfFieldValueCriteria, org.hibernate.Criteria ecrfFieldCriteria,
		org.hibernate.Criteria probandListEntryCriteria, Long probandListEntryId, Long ecrfFieldId) {
	DetachedCriteria subQuery = createEcrfFieldValueDetachedCriteriaMaxId(ecrfFieldValueCriteria, ecrfFieldCriteria, probandListEntryCriteria, probandListEntryId, ecrfFieldId);
	subQuery.add(Restrictions.or(Restrictions.isNull("index"),
			Restrictions.eqProperty("index", ecrfFieldValueCriteria.getAlias() + ".index")));
	ecrfFieldValueCriteria.add(Subqueries.propertyEq("id", subQuery));
}
 
Example #19
Source File: SimplePageToolDaoImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public SimplePageItem findNextItemOnPage(long pageId, int sequence) {
        DetachedCriteria d = DetachedCriteria.forClass(SimplePageItem.class).add(Restrictions.eq("pageId", pageId)).
	    add(Restrictions.eq("sequence", sequence+1));

	List<SimplePageItem> list = (List<SimplePageItem>) getHibernateTemplate().findByCriteria(d);

	if (list == null || list.size() < 1)
	    return null;
		
	return list.get(0);
}
 
Example #20
Source File: SimplePageToolDaoImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public SimplePageItem findNextPageItemOnPage(long pageId, int sequence) {
        DetachedCriteria d = DetachedCriteria.forClass(SimplePageItem.class).add(Restrictions.eq("pageId", pageId)).
	    add(Restrictions.eq("sequence", sequence+1)).
	    add(Restrictions.eq("type",SimplePageItem.PAGE));

	List<SimplePageItem> list = (List<SimplePageItem>) getHibernateTemplate().findByCriteria(d);

	if (list == null || list.size() < 1)
	    return null;
		
	return list.get(0);
}
 
Example #21
Source File: BaseServiceImpl.java    From TinyMooc with Apache License 2.0 5 votes vote down vote up
/**
 * 计算总页数(入参为detachedCriteria)
 *
 * @param dCriteria
 * @param pageSize
 * @return
 */
@Transactional(readOnly = true)
public int countTotalPage(DetachedCriteria dCriteria, int pageSize) {
    Criteria criteria = dCriteria.getExecutableCriteria(getCurrentSession());
    int totalRecord = ((Long) criteria
            .setProjection(Projections.rowCount()).uniqueResult())
            .intValue();
    criteria.setProjection(null);
    int totalPage = (int) Math.ceil(((double) totalRecord / pageSize));
    return totalPage;
}
 
Example #22
Source File: PermissionDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected Collection<Permission> handleFindByServiceMethodUser(
		String serviceMethod, Long userId, Boolean profilePermissionActive,
		Boolean userPermissionProfileActive) throws Exception {
	org.hibernate.Criteria permissionCritria = createPermissionCriteria();
	if (serviceMethod != null) {
		permissionCritria.add(Restrictions.eq("serviceMethod", serviceMethod));
	}
	if (userId != null || profilePermissionActive != null || userPermissionProfileActive != null) {
		org.hibernate.Criteria profilePermissionCritria = permissionCritria.createCriteria("profilePermissions", CriteriaSpecification.LEFT_JOIN);
		if (profilePermissionActive != null) {
			profilePermissionCritria.add(Restrictions.eq("active", profilePermissionActive.booleanValue()));
		}
		if (userId != null || userPermissionProfileActive != null) {
			DetachedCriteria subQuery = DetachedCriteria.forClass(UserPermissionProfileImpl.class, "userPermissionProfile"); // IMPL!!!!
			subQuery.setProjection(Projections.projectionList().add(Projections.property("profile")));
			if (userId != null) {
				subQuery.add(Restrictions.eq("user.id", userId.longValue()));
			}
			if (userPermissionProfileActive != null) {
				subQuery.add(Restrictions.eq("active", userPermissionProfileActive.booleanValue()));
			}
			profilePermissionCritria.add(Subqueries.propertyIn("profile", subQuery));
		}
	}
	return permissionCritria.list();
}
 
Example #23
Source File: SignupMeetingDaoImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@SuppressWarnings("unchecked")
public List<SignupMeeting> getSignupMeetingsInSites(List<String> siteIds, Date startDate,
		Date endDate) {
	DetachedCriteria criteria = DetachedCriteria.forClass(
			SignupMeeting.class).setResultTransformer(
			Criteria.DISTINCT_ROOT_ENTITY)
			.add(Restrictions.ge("endTime", startDate))
			.add(Restrictions.lt("startTime", endDate))
			.addOrder(Order.asc("startTime")).createCriteria("signupSites")
			.add(Restrictions.in("siteId", siteIds));

	return (List<SignupMeeting>) getHibernateTemplate().findByCriteria(criteria);
}
 
Example #24
Source File: SimplePageToolDaoImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public SimplePageComment findCommentById(long commentId) {
	DetachedCriteria d = DetachedCriteria.forClass(SimplePageComment.class).add(Restrictions.eq("id", commentId));
	List<SimplePageComment> list = (List<SimplePageComment>) getHibernateTemplate().findByCriteria(d);
	
	if(list.size() > 0) {
		return list.get(0);
	}else {
		return null;
	}
}
 
Example #25
Source File: SignupMeetingDaoImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@SuppressWarnings("unchecked")
public List<SignupMeeting> getAutoReminderSignupMeetings(Date startDate,
		Date endDate) {
	DetachedCriteria criteria = DetachedCriteria.forClass(
			SignupMeeting.class).setResultTransformer(
			Criteria.DISTINCT_ROOT_ENTITY).add(Restrictions.eq("autoReminder", true))
			//.add(Restrictions.between("startTime", startDate, endDate))
			.add(Restrictions.le("startTime", endDate))
			.add(Restrictions.ge("endTime",startDate))
			.addOrder(Order.asc("startTime"));		

	return (List<SignupMeeting>) getHibernateTemplate().findByCriteria(criteria);
}
 
Example #26
Source File: SimplePageToolDaoImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public List<SimplePageLogEntry> getStudentPageLogEntries(long itemId, String userId) {		
	DetachedCriteria d = DetachedCriteria.forClass(SimplePageLogEntry.class).add(Restrictions.eq("userId", userId))
			.add(Restrictions.eq("itemId", itemId))
			.add(Restrictions.isNotNull("studentPageId"));

	return (List<SimplePageLogEntry>) getHibernateTemplate().findByCriteria(d);
}
 
Example #27
Source File: HibernateGenericStore.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Creates a Criteria for the implementation Class type.
 * <p>
 * Please note that sharing is not considered.
 *
 * @return a Criteria instance.
 */
@Deprecated
public final Criteria getCriteria()
{
    DetachedCriteria criteria = DetachedCriteria.forClass( getClazz() );

    preProcessDetachedCriteria( criteria );

    return getExecutableCriteria( criteria );
}
 
Example #28
Source File: GoodsCommentDaoImpl.java    From Mall-Server with MIT License 5 votes vote down vote up
@Override
public int getCountByGoodsId(int goodsId) {
    DetachedCriteria criteria = DetachedCriteria.forClass(GoodsComment.class);

    criteria.add(Restrictions.eq("goodsid", goodsId));
    criteria.setProjection(Projections.rowCount());

    Object obj  = template.findByCriteria(criteria).get(0);
    Long longObj = (Long) obj;
    int count = longObj.intValue();
    return count;
}
 
Example #29
Source File: CriteriaQueryEngine.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
@SuppressWarnings( "unchecked" )
public int count( Query query )
{
    Schema schema = query.getSchema();
    InternalHibernateGenericStore<?> store = getStore( (Class<? extends IdentifiableObject>) schema.getKlass() );

    if ( store == null )
    {
        return 0;
    }

    if ( query.getUser() == null )
    {
        query.setUser( currentUserService.getCurrentUser() );
    }

    if ( !query.isPlannedQuery() )
    {
        QueryPlan queryPlan = queryPlanner.planQuery( query, true );
        query = queryPlan.getPersistedQuery();
    }

    DetachedCriteria detachedCriteria = buildCriteria( store.getSharingDetachedCriteria( query.getUser() ), query );
    Criteria criteria = store.getCriteria();

    if ( criteria == null )
    {
        return 0;
    }

    return ((Number) criteria.add( Subqueries.propertyIn( "id", detachedCriteria ) )
        .setProjection( Projections.countDistinct( "id" ) )
        .uniqueResult()).intValue();
}
 
Example #30
Source File: SimplePageToolDaoImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public List<SimplePageItem> findTopLevelPageItemsBySakaiIds(List<String> ids) {
	DetachedCriteria d = DetachedCriteria.forClass(SimplePageItem.class)
		.add(Restrictions.in("sakaiId", ids))
		.add(Restrictions.eq("pageId", 0L))
		.add(Restrictions.eq("type",SimplePageItem.PAGE));

	List<SimplePageItem> list = (List<SimplePageItem>) getHibernateTemplate().findByCriteria(d);

	if (list == null || list.size() < 1) {
		return null;
	}

	return list;
}