Java Code Examples for org.hibernate.criterion.Restrictions#disjunction()

The following examples show how to use org.hibernate.criterion.Restrictions#disjunction() . 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: CrossNavigationDAOImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public List<SbiCrossNavigation> listNavigationsByDocumentAndParameters(Integer documentId, List<Integer> inputParameters, List<Integer> outputParameters,
		Session session) {
	// load cross navigation item
	Disjunction disj = Restrictions.disjunction();
	if (!inputParameters.isEmpty()) {
		disj.add(Restrictions.conjunction().add(Restrictions.eq("_par.fromType", 1)).add(Restrictions.in("_par.fromKeyId", inputParameters)));
		disj.add(Restrictions.in("_par.toKeyId", inputParameters));
	}
	if (!outputParameters.isEmpty()) {
		disj.add(Restrictions.conjunction().add(Restrictions.eq("_par.fromType", 0)).add(Restrictions.in("_par.fromKeyId", outputParameters)));
	}
	disj.add(Restrictions.conjunction().add(Restrictions.eq("_par.fromType", 2)).add(Restrictions.eq("_par.fromKeyId", documentId)));

	List ret = session.createCriteria(SbiCrossNavigation.class).createAlias("sbiCrossNavigationPars", "_par").add(disj).list();
	return ret;
}
 
Example 2
Source File: ShoppingCartDaoImpl.java    From Mall-Server with MIT License 5 votes vote down vote up
@Override
@Transactional
public void delShoppingCart(int[] cart) {
    DetachedCriteria criteria=DetachedCriteria.forClass(ShoppingCart.class);
    Disjunction dis = Restrictions.disjunction();
    for(int item : cart) {
        System.out.println(item);
        dis.add(Restrictions.eq("id", item));
    }
    criteria.add(dis);
    List<ShoppingCart> list = (List<ShoppingCart>) template.findByCriteria(criteria);
    template.deleteAll(list);
}
 
Example 3
Source File: CriteriaQueryEngine.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private org.hibernate.criterion.Junction getHibernateJunction( Junction.Type type )
{
    switch ( type )
    {
        case AND:
            return Restrictions.conjunction();
        case OR:
            return Restrictions.disjunction();
    }

    return Restrictions.conjunction();
}
 
Example 4
Source File: CriterionMultipleValueSupport.java    From base-framework with Apache License 2.0 5 votes vote down vote up
public Criterion build(PropertyFilter filter) {
	Object value = convertMatchValue(filter.getMatchValue(), filter.getFieldType());
	Criterion criterion = null;
	if (filter.hasMultiplePropertyNames()) {
		Disjunction disjunction = Restrictions.disjunction();
		for (String propertyName:filter.getPropertyNames()) {
			disjunction.add(build(propertyName,value));
		}
		criterion = disjunction;
	} else {
		criterion = build(filter.getSinglePropertyName(),value);
	}
	return criterion;
}
 
Example 5
Source File: SUSEProductFactory.java    From uyuni with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Find a {@link SUSEProduct} given by name, version, release and arch.
 * @param name name
 * @param version version or null
 * @param release release or null
 * @param arch arch or null
 * @param imprecise if true, allow returning products with NULL name, version or
 * release even if the corresponding parameters are not null
 * @return product or null if it is not found
 */
@SuppressWarnings("unchecked")
public static SUSEProduct findSUSEProduct(String name, String version, String release,
        String arch, boolean imprecise) {

    Criteria c = getSession().createCriteria(SUSEProduct.class);
    c.add(Restrictions.eq("name", name.toLowerCase()));

    Disjunction versionCriterion = Restrictions.disjunction();
    if (imprecise || version == null) {
        versionCriterion.add(Restrictions.isNull("version"));
    }
    if (version != null) {
        versionCriterion.add(Restrictions.eq("version", version.toLowerCase()));
    }
    c.add(versionCriterion);

    Disjunction releaseCriterion = Restrictions.disjunction();
    if (imprecise || release == null) {
        releaseCriterion.add(Restrictions.isNull("release"));
    }
    if (release != null) {
        releaseCriterion.add(Restrictions.eq("release", release.toLowerCase()));
    }
    c.add(releaseCriterion);

    Disjunction archCriterion = Restrictions.disjunction();
    if (imprecise || arch == null) {
        archCriterion.add(Restrictions.isNull("arch"));
    }
    if (arch != null) {
        archCriterion.add(Restrictions.eq("arch",
                PackageFactory.lookupPackageArchByLabel(arch)));
    }
    c.add(archCriterion);

    c.addOrder(Order.asc("name")).addOrder(Order.asc("version"))
            .addOrder(Order.asc("release")).addOrder(Order.asc("arch"));

    List<SUSEProduct> result = c.list();
    return result.isEmpty() ? null : result.get(0);
}
 
Example 6
Source File: BIObjectDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public List<BIObject> loadAllBIObjectsBySearchKey(String searchKey, String attributes) throws EMFUserError {
	logger.debug("IN");
	Session aSession = null;
	Transaction tx = null;
	List result = new ArrayList();
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();
		Criteria hibQuery = aSession.createCriteria(SbiObjects.class);

		Criterion labelCriterion = EscapedLikeRestrictions.ilikeEscaped("label", searchKey, MatchMode.ANYWHERE);
		Criterion nameCriterion = EscapedLikeRestrictions.ilikeEscaped("name", searchKey, MatchMode.ANYWHERE);
		Criterion descrCriterion = EscapedLikeRestrictions.ilikeEscaped("descr", searchKey, MatchMode.ANYWHERE);

		if ("LABEL".equalsIgnoreCase(attributes)) {
			hibQuery.add(labelCriterion);
		} else if ("NAME".equalsIgnoreCase(attributes)) {
			hibQuery.add(nameCriterion);
		} else if ("DESCRIPTION".equalsIgnoreCase(attributes)) {
			hibQuery.add(descrCriterion);
		} else {
			Disjunction disjunction = Restrictions.disjunction();
			disjunction.add(labelCriterion);
			disjunction.add(nameCriterion);
			disjunction.add(descrCriterion);
			hibQuery.add(disjunction);
		}

		List hibList = hibQuery.list();
		Iterator it = hibList.iterator();
		Set<Integer> resultIds = new HashSet<>();
		while (it.hasNext()) {
			SbiObjects next = (SbiObjects) it.next();
			Integer id = next.getBiobjId();
			if (!resultIds.contains(id)) {
				resultIds.add(id);
				result.add(toBIObject(next, aSession));
			}
		}

		tx.commit();
	} catch (HibernateException he) {
		logger.error("HibernateException", he);
		if (tx != null) {
			tx.rollback();
		}
		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
	} finally {
		if (aSession != null && aSession.isOpen()) {
			aSession.close();
		}
		logger.debug("OUT");
	}
	return result;
}
 
Example 7
Source File: SbiDataSetDAOImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public List<SbiDataSet> loadPaginatedSearchSbiDataSet(String search, Integer page, Integer item_per_page, IEngUserProfile finalUserProfile,
		Boolean seeTechnical, Integer[] ids, boolean spatialOnly) {
	Session session = null;
	List<SbiDataSet> list = null;

	try {
		session = getSession();
		Criteria c = session.createCriteria(SbiDataSet.class);
		c.addOrder(Order.asc("label"));

		if (page != null && item_per_page != null) {
			c.setFirstResult((page - 1) * item_per_page);
			c.setMaxResults(item_per_page);
		}

		c.add(Restrictions.like("label", search == null ? "" : search, MatchMode.ANYWHERE).ignoreCase());
		c.add(Restrictions.eq("active", true));

		if (ids != null && ids.length > 0) {
			c.add(Restrictions.in("id.dsId", ids));
		}

		if (spatialOnly) {
			c.add(Restrictions.like("dsMetadata", IFieldMetaData.FieldType.SPATIAL_ATTRIBUTE.toString(), MatchMode.ANYWHERE));
		}

		if (finalUserProfile != null) {

			logger.debug("For final user take only owned, enterprise and shared");

			SbiDomains scopeUserDomain = DAOFactory.getDomainDAO().loadSbiDomainByCodeAndValue("DS_SCOPE", SpagoBIConstants.DS_SCOPE_USER);
			SbiDomains scopeEnterpriseDomain = DAOFactory.getDomainDAO().loadSbiDomainByCodeAndValue("DS_SCOPE", SpagoBIConstants.DS_SCOPE_ENTERPRISE);
			SbiDomains scopeTechnicalDomain = DAOFactory.getDomainDAO().loadSbiDomainByCodeAndValue("DS_SCOPE", SpagoBIConstants.DS_SCOPE_TECHNICAL);

			Disjunction or = Restrictions.disjunction();

			// OWNER OR

			// take owned datasets
			or.add(Restrictions.eq("owner", ((UserProfile) finalUserProfile).getUserId().toString()));

			// get categories
			Set<Domain> categoryList = UserUtilities.getDataSetCategoriesByUser(finalUserProfile);

			if (categoryList != null) {
				if (categoryList.size() > 0) {
					SbiDomains[] categoryArray = new SbiDomains[categoryList.size()];
					int i = 0;
					for (Iterator iterator = categoryList.iterator(); iterator.hasNext();) {
						Domain domain = (Domain) iterator.next();
						String domainCd = domain.getDomainCode();
						String valueCd = domain.getValueCd();
						SbiDomains sbiDomain = DAOFactory.getDomainDAO().loadSbiDomainByCodeAndValue(domainCd, valueCd);
						categoryArray[i] = sbiDomain;
						i++;
					}
					// (IN CATEGORY AND (SCOPE=USER OR SCOPE=ENTERPRISE)) OR SCOPE=TECHNICAL
					Conjunction andCategories = Restrictions.conjunction();
					andCategories.add(Restrictions.in("category", categoryArray));

					Disjunction orScope = Restrictions.disjunction();
					orScope.add(Restrictions.eq("scope", scopeUserDomain));
					orScope.add(Restrictions.eq("scope", scopeEnterpriseDomain));

					andCategories.add(orScope);

					if (seeTechnical != null && seeTechnical) {
						Disjunction orTechnical = Restrictions.disjunction();
						orTechnical.add(andCategories);
						orTechnical.add(Restrictions.eq("scope", scopeTechnicalDomain));
						or.add(orTechnical);
					} else {
						or.add(andCategories);
					}

				}
			} else {
				// if no categoryList take also all USER and ENTERPRISE dataset
				// SCOPE=USER OR SCOPE=ENTERPRISE)
				or.add(Restrictions.eq("scope", scopeUserDomain));
				or.add(Restrictions.eq("scope", scopeEnterpriseDomain));
			}

			c.add(or);
		}

		list = c.list();
		initialize(list);

	} catch (Exception e) {
		throw new SpagoBIDAOException("An unexpected error occured while loading datasets", e);
	} finally {
		if (session != null && session.isOpen()) {
			session.close();
		}
		logger.debug("OUT");
	}
	return list;
}
 
Example 8
Source File: VisitScheduleItemDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 4 votes vote down vote up
private static LinkedHashMap<String, Projection> applyExpandDateModeCriterions(org.hibernate.Criteria visitScheduleItemCriteria, Long probandId, Timestamp from, Timestamp to,
		org.hibernate.criterion.Criterion or) {
	// cartesian product <visitscheduleitems> x <start tag values> x <stop tag values>
	org.hibernate.Criteria startTagValuesCriteria = visitScheduleItemCriteria.createCriteria("startTag", CriteriaSpecification.LEFT_JOIN)
			.createCriteria("tagValues", "startTagValues", CriteriaSpecification.LEFT_JOIN);
	org.hibernate.Criteria startTagValuesValueCriteria = startTagValuesCriteria.createCriteria("value",
			CriteriaSpecification.LEFT_JOIN);
	org.hibernate.Criteria stopTagValuesCriteria = visitScheduleItemCriteria.createCriteria("stopTag", CriteriaSpecification.LEFT_JOIN).createCriteria("tagValues",
			"stopTagValues", CriteriaSpecification.LEFT_JOIN);
	org.hibernate.Criteria stopTagValuesValueCriteria = stopTagValuesCriteria.createCriteria("value", CriteriaSpecification.LEFT_JOIN);
	// from the cross product, remove those with start+stop values of different probands. also include rows without existing stop tag values
	visitScheduleItemCriteria.add(CriteriaUtil.applyOr(
			Restrictions.or(Restrictions.eqProperty("startTagValues.listEntry.id", "stopTagValues.listEntry.id"), Restrictions.isNull("stopTagValues.listEntry.id")), or));
	// narrow to particular proband, if given
	org.hibernate.Criteria startTagValuesListEntryCriteria = startTagValuesCriteria.createCriteria("listEntry", "startTagValuesListEntry", CriteriaSpecification.LEFT_JOIN);
	if (probandId != null) {
		startTagValuesListEntryCriteria.add(CriteriaUtil.applyOr(Restrictions.or(Restrictions.isNull("proband.id"), Restrictions.eq("proband.id", probandId.longValue())), or));
	}
	// only rows with proband group matching the group of the visitschelute item (or those with no group)
	visitScheduleItemCriteria
			.add(CriteriaUtil.applyOr(Restrictions.or(Restrictions.isNull("startTagValuesListEntry.id"),
					Restrictions.or(Restrictions.eqProperty("startTagValuesListEntry.group.id", "group.id"), Restrictions.isNull("group.id"))), or));
	CriteriaQueryTranslator translator = CriteriaUtil.getCriteriaQueryTranslator(visitScheduleItemCriteria);
	// prepare sql fragments:
	String offsetSql = translator.getColumn(visitScheduleItemCriteria, "offsetSeconds");
	String durationSql = translator.getColumn(visitScheduleItemCriteria, "duration");
	String tagStartSql = translator.getColumn(startTagValuesValueCriteria, "timestampValue");
	String tagStopSql = translator.getColumn(stopTagValuesValueCriteria, "timestampValue");
	String tagStartOffsetSql = MessageFormat.format(Settings.getString(SettingCodes.SQL_ADD_SECONDS_TERM, Bundle.SETTINGS, null),
			tagStartSql, offsetSql);
	String tagStopOffsetSql = MessageFormat.format(Settings.getString(SettingCodes.SQL_ADD_SECONDS_TERM, Bundle.SETTINGS, null),
			tagStopSql, offsetSql);
	String durationStopOffsetSql = MessageFormat.format(Settings.getString(SettingCodes.SQL_ADD_SECONDS_TERM, Bundle.SETTINGS, null),
			tagStartOffsetSql, durationSql);
	String probandIdSql = translator.getColumn(startTagValuesListEntryCriteria, "proband.id");
	// date filtering
	Junction junction = Restrictions.disjunction();
	if (or != null) {
		junction.add(or);
	}
	if (from != null || to != null) {
		junction.add(Restrictions.and(Restrictions.eq("mode", VisitScheduleDateMode.STATIC), CriteriaUtil.getClosedIntervalCriterion(from, to, null)));
		junction.add(Restrictions.and(Restrictions.eq("mode", VisitScheduleDateMode.TAGS),
				Restrictions.and(Restrictions.sqlRestriction("(" + tagStartSql + ") < (" + tagStopSql + ")"),
						CriteriaUtil.getClosedIntervalCriterion(from, to, null, tagStartOffsetSql, tagStopOffsetSql))));
		junction.add(
				Restrictions.and(Restrictions.eq("mode", VisitScheduleDateMode.TAG_DURATION), Restrictions.and(Restrictions.sqlRestriction("(" + tagStartSql + ") is not null"),
						CriteriaUtil.getClosedIntervalCriterion(from, to, null, tagStartOffsetSql, durationStopOffsetSql))));
		visitScheduleItemCriteria.add(junction);
	} else {
		junction.add(Restrictions.eq("mode", VisitScheduleDateMode.STATIC));
		junction.add(Restrictions.and(Restrictions.eq("mode", VisitScheduleDateMode.TAGS), Restrictions.sqlRestriction("(" + tagStartSql + ") < (" + tagStopSql + ")")));
		junction.add(Restrictions.and(Restrictions.eq("mode", VisitScheduleDateMode.TAG_DURATION), Restrictions.sqlRestriction("(" + tagStartSql + ") is not null")));
	}
	visitScheduleItemCriteria.add(junction); //no stales any more
	LinkedHashMap<String, Projection> sqlColumns = new LinkedHashMap<String, Projection>();
	sqlColumns.put("tagStart", new SQLProjection(
			tagStartOffsetSql + " as tagStart",
			new String[] { "tagStart" },
			new org.hibernate.type.Type[] { Hibernate.TIMESTAMP },
			tagStartOffsetSql));
	sqlColumns.put("tagStop", new SQLProjection(
			tagStopOffsetSql + " as tagStop",
			new String[] { "tagStop" },
			new org.hibernate.type.Type[] { Hibernate.TIMESTAMP },
			tagStopOffsetSql));
	sqlColumns.put("durationStop", new SQLProjection(
			durationStopOffsetSql + " as durationStop",
			new String[] { "durationStop" },
			new org.hibernate.type.Type[] { Hibernate.TIMESTAMP },
			durationStopOffsetSql));
	sqlColumns.put("probandId", new SQLProjection(
			probandIdSql + " as probandId",
			new String[] { "probandId" },
			new org.hibernate.type.Type[] { Hibernate.LONG },
			probandIdSql));
	return sqlColumns;
}
 
Example 9
Source File: HibernateIdentifiableObjectStore.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Creates a detached criteria with data sharing restrictions relative to the
 * given user and access string.
 *
 * @param user the user.
 * @param access the access string.
 * @return a DetachedCriteria.
 */
private DetachedCriteria getDataSharingDetachedCriteria( UserInfo user, String access )
{
    DetachedCriteria criteria = DetachedCriteria.forClass( getClazz(), "c" );

    if ( user == null || !dataSharingEnabled( user ) )
    {
        return criteria;
    }

    Assert.notNull( user, "User argument can't be null." );

    Disjunction disjunction = Restrictions.disjunction();

    disjunction.add( Restrictions.like( "c.publicAccess", access ) );
    disjunction.add( Restrictions.isNull( "c.publicAccess" ) );

    DetachedCriteria userGroupDetachedCriteria = DetachedCriteria.forClass( getClazz(), "ugdc" );
    userGroupDetachedCriteria.createCriteria( "ugdc.userGroupAccesses", "uga" );
    userGroupDetachedCriteria.createCriteria( "uga.userGroup", "ug" );
    userGroupDetachedCriteria.createCriteria( "ug.members", "ugm" );

    userGroupDetachedCriteria.add( Restrictions.eqProperty( "ugdc.id", "c.id" ) );
    userGroupDetachedCriteria.add( Restrictions.eq( "ugm.id", user.getId() ) );
    userGroupDetachedCriteria.add( Restrictions.like( "uga.access", access ) );

    userGroupDetachedCriteria.setProjection( Property.forName( "uga.id" ) );

    disjunction.add( Subqueries.exists( userGroupDetachedCriteria ) );

    DetachedCriteria userDetachedCriteria = DetachedCriteria.forClass( getClazz(), "udc" );
    userDetachedCriteria.createCriteria( "udc.userAccesses", "ua" );
    userDetachedCriteria.createCriteria( "ua.user", "u" );

    userDetachedCriteria.add( Restrictions.eqProperty( "udc.id", "c.id" ) );
    userDetachedCriteria.add( Restrictions.eq( "u.id", user.getId() ) );
    userDetachedCriteria.add( Restrictions.like( "ua.access", access ) );

    userDetachedCriteria.setProjection( Property.forName( "ua.id" ) );

    disjunction.add( Subqueries.exists( userDetachedCriteria ) );

    criteria.add( disjunction );

    return criteria;
}
 
Example 10
Source File: HibernateIdentifiableObjectStore.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Creates a detached criteria with sharing restrictions relative to the given
 * user and access string.
 *
 * @param user   the user.
 * @param access the access string.
 * @return a DetachedCriteria.
 */
private DetachedCriteria getSharingDetachedCriteria( UserInfo user, String access )
{
    DetachedCriteria criteria = DetachedCriteria.forClass( getClazz(), "c" );

    preProcessDetachedCriteria( criteria );

    if ( !sharingEnabled( user ) || user == null )
    {
        return criteria;
    }

    Assert.notNull( user, "User argument can't be null." );

    Disjunction disjunction = Restrictions.disjunction();

    disjunction.add( Restrictions.like( "c.publicAccess", access ) );
    disjunction.add( Restrictions.isNull( "c.publicAccess" ) );
    disjunction.add( Restrictions.isNull( "c.user.id" ) );
    disjunction.add( Restrictions.eq( "c.user.id", user.getId() ) );

    DetachedCriteria userGroupDetachedCriteria = DetachedCriteria.forClass( getClazz(), "ugdc" );
    userGroupDetachedCriteria.createCriteria( "ugdc.userGroupAccesses", "uga" );
    userGroupDetachedCriteria.createCriteria( "uga.userGroup", "ug" );
    userGroupDetachedCriteria.createCriteria( "ug.members", "ugm" );

    userGroupDetachedCriteria.add( Restrictions.eqProperty( "ugdc.id", "c.id" ) );
    userGroupDetachedCriteria.add( Restrictions.eq( "ugm.id", user.getId() ) );
    userGroupDetachedCriteria.add( Restrictions.like( "uga.access", access ) );

    userGroupDetachedCriteria.setProjection( Property.forName( "uga.id" ) );

    disjunction.add( Subqueries.exists( userGroupDetachedCriteria ) );

    DetachedCriteria userDetachedCriteria = DetachedCriteria.forClass( getClazz(), "udc" );
    userDetachedCriteria.createCriteria( "udc.userAccesses", "ua" );
    userDetachedCriteria.createCriteria( "ua.user", "u" );

    userDetachedCriteria.add( Restrictions.eqProperty( "udc.id", "c.id" ) );
    userDetachedCriteria.add( Restrictions.eq( "u.id", user.getId() ) );
    userDetachedCriteria.add( Restrictions.like( "ua.access", access ) );

    userDetachedCriteria.setProjection( Property.forName( "ua.id" ) );

    disjunction.add( Subqueries.exists( userDetachedCriteria ) );

    criteria.add( disjunction );

    return criteria;
}
 
Example 11
Source File: AssessmentGradingFacadeQueries.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public Set<PublishedItemData> getItemSet(final Long publishedAssessmentId, final Long sectionId) {

        final HibernateCallback<List<Long>> hcb = session -> {
            Query q = session.createQuery(
                    "select distinct p.itemId " +
                            "from PublishedItemData p, AssessmentGradingData a, ItemGradingData i " +
                            "where a.publishedAssessmentId = :id and a.forGrade = :forgrade and p.section.id = :sectionid " +
                            "and i.assessmentGradingId = a.assessmentGradingId " +
                            "and p.itemId = i.publishedItemId and a.status > :status ");
            q.setLong("id", publishedAssessmentId);
            q.setBoolean("forgrade", true);
            q.setLong("sectionid", sectionId);
            q.setInteger("status", AssessmentGradingData.REMOVED);
            return q.list();
        };
        List<Long> itemIds = getHibernateTemplate().execute(hcb);

        if (itemIds.isEmpty()) {
            return new HashSet<>();
        }

        final HibernateCallback<List<PublishedItemData>> hcb2 = session -> {

            final Criteria criteria = session.createCriteria(PublishedItemData.class);
            if (itemIds.size() > 1000) {
                final Set<Long> ids = new HashSet<>();
                Disjunction disjunction = Restrictions.disjunction();

                for (Long id : itemIds) {
                    if (ids.size() < 1000) {
                        ids.add(id);
                    } else {
                        criteria.add(disjunction.add(Restrictions.in("itemId", ids)));
                        ids.clear();
                    }
                }
            } else {
                criteria.add(Restrictions.in("itemId", itemIds));
            }
            return criteria.list();
        };

        List<PublishedItemData> publishedItems = getHibernateTemplate().execute(hcb2);

        return new HashSet<>(publishedItems);
    }
 
Example 12
Source File: AssessmentGradingFacadeQueries.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public Set<PublishedItemData> getItemSet(final Long publishedAssessmentId, final Long sectionId) {

        final HibernateCallback<List<Long>> hcb = session -> {
            Query q = session.createQuery(
                    "select distinct p.itemId " +
                            "from PublishedItemData p, AssessmentGradingData a, ItemGradingData i " +
                            "where a.publishedAssessmentId = :id and a.forGrade = :forgrade and p.section.id = :sectionid " +
                            "and i.assessmentGradingId = a.assessmentGradingId " +
                            "and p.itemId = i.publishedItemId and a.status > :status ");
            q.setLong("id", publishedAssessmentId);
            q.setBoolean("forgrade", true);
            q.setLong("sectionid", sectionId);
            q.setInteger("status", AssessmentGradingData.REMOVED);
            return q.list();
        };
        List<Long> itemIds = getHibernateTemplate().execute(hcb);

        if (itemIds.isEmpty()) {
            return new HashSet<>();
        }

        final HibernateCallback<List<PublishedItemData>> hcb2 = session -> {

            final Criteria criteria = session.createCriteria(PublishedItemData.class);
            if (itemIds.size() > 1000) {
                final Set<Long> ids = new HashSet<>();
                Disjunction disjunction = Restrictions.disjunction();

                for (Long id : itemIds) {
                    if (ids.size() < 1000) {
                        ids.add(id);
                    } else {
                        criteria.add(disjunction.add(Restrictions.in("itemId", ids)));
                        ids.clear();
                    }
                }
            } else {
                criteria.add(Restrictions.in("itemId", itemIds));
            }
            return criteria.list();
        };

        List<PublishedItemData> publishedItems = getHibernateTemplate().execute(hcb2);

        return new HashSet<>(publishedItems);
    }