Example usage for org.hibernate.criterion Restrictions conjunction

List of usage examples for org.hibernate.criterion Restrictions conjunction

Introduction

In this page you can find the example usage for org.hibernate.criterion Restrictions conjunction.

Prototype

public static Conjunction conjunction() 

Source Link

Document

Group expressions together in a single conjunction (A and B and C...).

Usage

From source file:com.wisemapping.dao.MindmapManagerImpl.java

License:Open Source License

public List<MindMap> search(MindMapCriteria criteria, int maxResult) {
    final Criteria hibernateCriteria = getSession().createCriteria(MindMap.class);
    //always search public maps
    hibernateCriteria.add(Restrictions.like("public", Boolean.TRUE));

    if (criteria != null) {
        final Junction junction;
        if (criteria.isOrCriteria()) {
            junction = Restrictions.disjunction();
        } else {//w w  w.j  a va  2  s . c o m
            junction = Restrictions.conjunction();
        }

        if (criteria.getTitle() != null && criteria.getTitle().length() > 0) {
            final SimpleExpression titleRestriction = Restrictions.like("title",
                    "%" + criteria.getTitle() + "%");
            junction.add(titleRestriction);
        }

        if (criteria.getDescription() != null && criteria.getDescription().length() > 0) {
            final SimpleExpression descriptionRestriction = Restrictions.like("description",
                    "%" + criteria.getDescription() + "%");
            junction.add(descriptionRestriction);
        }
        if (criteria.getTags().size() > 0) {
            for (String tag : criteria.getTags()) {
                final SimpleExpression tagRestriction = Restrictions.like("tags", "%" + tag + "%");
                junction.add(tagRestriction);
            }
        }

        hibernateCriteria.add(junction);
    }
    //        if (maxResult>0)
    //        {
    //            hibernateCriteria.setMaxResults(maxResult);
    //        }
    return hibernateCriteria.list();
}

From source file:de.cosmocode.hibernate.CustomRestrictions.java

License:Apache License

/**
 * Group expressions together in a single conjunction (A and B and C...).
 * /*from w  w w  .j  a v  a2s  .  c  o m*/
 * @param first the first {@link Criterion}
 * @param second the second {@link Criterion}
 * @param rest the rest
 * @return a {@link Criterion} containing all parameters combined in conjuct style
 */
public static Criterion conjunction(Criterion first, Criterion second, Criterion... rest) {
    final Conjunction conjunction = Restrictions.conjunction();
    conjunction.add(first).add(second);
    for (Criterion criterion : rest) {
        conjunction.add(criterion);
    }
    return conjunction;
}

From source file:de.decidr.model.commands.user.GetAdministratedWorkflowModelsCommand.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/*from  w  w  w. j a  va2 s  . c o  m*/
public void transactionAllowed(TransactionStartedEvent evt) throws TransactionException {
    result = null;

    // does the user exist? returning an empty list might be ambigous.
    String hql = "select u.id from User u where u.id = :userId";
    Object id = evt.getSession().createQuery(hql).setLong("userId", getUserId()).setMaxResults(1)
            .uniqueResult();

    if (id == null) {
        throw new EntityNotFoundException(User.class, getUserId());
    }

    /*
     * Criteria that represent the following query:
     * 
     * "from WorkflowModel w where w.tenant.id = DEFAULT_TENANT_ID or
     * (exists(from UserAdministratesWorkflowModel rel where
     * rel.workflowModel = w and rel.user.id = :userId) or w.tenant.admin.id
     * = :userId) or exists (from SystemSettings s where s.admin.id =
     * :userId))"
     */
    PaginatingCriteria criteria = new PaginatingCriteria(WorkflowModel.class, "m", evt.getSession());

    /*
     * A user administers a workflow model if there's an explicit
     * relationship.
     */
    DetachedCriteria explicitWorkflowAdminCriteria = DetachedCriteria
            .forClass(UserAdministratesWorkflowModel.class, "rel");
    explicitWorkflowAdminCriteria
            .add(Restrictions.conjunction().add(Restrictions.eqProperty("rel.workflowModel.id", "m.id"))
                    .add(Restrictions.eq("rel.user.id", getUserId())));

    /*
     * A user administers *any* workflow model if he is the super admin.
     */
    DetachedCriteria superAdminCriteria = DetachedCriteria.forClass(SystemSettings.class, "s");
    superAdminCriteria.add(Restrictions.eq("s.superAdmin.id", getUserId()));

    /*
     * Workaround for Hibernate issue HHH-993: Criteria subquery without
     * projection fails throwing NullPointerException.
     * 
     * Additionally, Mysql doesn't seem to like aliases in EXISTS
     * subqueries, so we have to explicitly specify "*"
     */
    explicitWorkflowAdminCriteria.setProjection(Projections.sqlProjection("*", new String[0], new Type[0]));
    superAdminCriteria.setProjection(Projections.sqlProjection("*", new String[0], new Type[0]));

    /*
     * Finally, a user administers a workflow model if he is the tenant
     * admin of the tenant that owns the model. We now add each criterion to
     * a disjuncion.
     */
    criteria.createAlias("tenant", "t");
    Disjunction allAdministrationCriteria = Restrictions.disjunction();
    allAdministrationCriteria.add(Subqueries.exists(superAdminCriteria));
    allAdministrationCriteria.add(Subqueries.exists(explicitWorkflowAdminCriteria));
    allAdministrationCriteria.add(Restrictions.eq("t.admin.id", getUserId()));

    /*
     * Everyone is a workflow admin for models within the default tenant.
     */
    criteria.add(Restrictions.disjunction().add(allAdministrationCriteria)
            .add(Restrictions.eq("m.tenant.id", DecidrGlobals.DEFAULT_TENANT_ID)));

    Filters.apply(criteria, filters, paginator);

    criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);

    result = criteria.list();
}

From source file:de.lemo.apps.integration.CourseDAOImpl.java

License:Open Source License

public boolean courseNeedsUpdate(final Long courseId) {
    Criteria criteria = this.session.createCriteria(Course.class);
    criteria.add(Restrictions.conjunction().add(Restrictions.eq("courseId", courseId))
            .add(Restrictions.eq("needUpdate", true)));
    final List<Course> results = criteria.list();
    if (results.size() == 0) {
        return false;
    }/*from  w  w  w .  j  a  v  a2  s  .  c o  m*/
    return true;
}

From source file:de.powerstaff.business.dao.hibernate.StatistikDAOHibernateImpl.java

License:Open Source License

@Override
public List<KontakthistorieEntry> kontakthistorie(final Date aDatumVon, final Date aDatumBis,
        final User aBenutzer) {
    return (List<KontakthistorieEntry>) getHibernateTemplate().execute(new HibernateCallback() {

        @Override//from  www .j  av a2 s .  c  o  m
        public Object doInHibernate(Session aSession) throws SQLException {
            List<KontakthistorieEntry> theResult = new ArrayList<KontakthistorieEntry>();

            Conjunction theRestrictions = Restrictions.conjunction();
            if (aDatumVon != null) {
                theRestrictions.add(Restrictions.ge("h.creationDate", aDatumVon));
            }
            if (aDatumBis != null) {
                theRestrictions.add(Restrictions.le("h.creationDate", aDatumBis));
            }
            if (aBenutzer != null) {
                theRestrictions.add(Restrictions.eq("h.creationUserID", aBenutzer.getUsername()));
            }

            // Freiberufler
            Criteria theCriteria = aSession.createCriteria(Freelancer.class, "p");
            theCriteria.createCriteria("history", "h");
            theCriteria.add(theRestrictions);

            ProjectionList theProjections = Projections.projectionList();
            theProjections.add(Projections.property("p.name1"));
            theProjections.add(Projections.property("p.name2"));
            theProjections.add(Projections.property("p.code"));
            theProjections.add(Projections.property("h.creationDate"));
            theProjections.add(Projections.property("h.creationUserID"));
            theProjections.add(Projections.property("h.type"));
            theProjections.add(Projections.property("h.description"));

            theCriteria.setProjection(theProjections);
            for (Object theResultObject : theCriteria.list()) {
                Object[] theResultArray = (Object[]) theResultObject;

                KontakthistorieEntry theEntry = new KontakthistorieEntry();
                theEntry.setName1((String) theResultArray[0]);
                theEntry.setName2((String) theResultArray[1]);
                theEntry.setCode((String) theResultArray[2]);
                Timestamp theTimestamp = (Timestamp) theResultArray[3];
                theEntry.setDatum(new Date(theTimestamp.getTime()));
                theEntry.setUserid((String) theResultArray[4]);
                theEntry.setType((HistoryType) theResultArray[5]);
                theEntry.setDescription((String) theResultArray[6]);

                theResult.add(theEntry);
            }

            // Partner
            theCriteria = aSession.createCriteria(Partner.class, "p");
            theCriteria.createCriteria("history", "h");
            theCriteria.add(theRestrictions);

            theProjections = Projections.projectionList();
            theProjections.add(Projections.property("p.name1"));
            theProjections.add(Projections.property("p.name2"));
            theProjections.add(Projections.property("h.creationDate"));
            theProjections.add(Projections.property("h.creationUserID"));
            theProjections.add(Projections.property("h.type"));
            theProjections.add(Projections.property("h.description"));

            theCriteria.setProjection(theProjections);
            for (Object theResultObject : theCriteria.list()) {
                Object[] theResultArray = (Object[]) theResultObject;

                KontakthistorieEntry theEntry = new KontakthistorieEntry();
                theEntry.setName1((String) theResultArray[0]);
                theEntry.setName2((String) theResultArray[1]);
                Timestamp theTimestamp = (Timestamp) theResultArray[2];
                theEntry.setDatum(new Date(theTimestamp.getTime()));
                theEntry.setUserid((String) theResultArray[3]);
                theEntry.setType((HistoryType) theResultArray[4]);
                theEntry.setDescription((String) theResultArray[5]);

                theResult.add(theEntry);
            }

            // Kunden
            theCriteria = aSession.createCriteria(Customer.class, "p");
            theCriteria.createCriteria("history", "h");
            theCriteria.add(theRestrictions);

            theProjections = Projections.projectionList();
            theProjections.add(Projections.property("p.name1"));
            theProjections.add(Projections.property("p.name2"));
            theProjections.add(Projections.property("h.creationDate"));
            theProjections.add(Projections.property("h.creationUserID"));
            theProjections.add(Projections.property("h.type"));
            theProjections.add(Projections.property("h.description"));

            theCriteria.setProjection(theProjections);
            for (Object theResultObject : theCriteria.list()) {
                Object[] theResultArray = (Object[]) theResultObject;

                KontakthistorieEntry theEntry = new KontakthistorieEntry();
                theEntry.setName1((String) theResultArray[0]);
                theEntry.setName2((String) theResultArray[1]);
                Timestamp theTimestamp = (Timestamp) theResultArray[2];
                theEntry.setDatum(new Date(theTimestamp.getTime()));
                theEntry.setUserid((String) theResultArray[3]);
                theEntry.setType((HistoryType) theResultArray[4]);
                theEntry.setDescription((String) theResultArray[5]);

                theResult.add(theEntry);
            }

            Collections.sort(theResult, new ReverseComparator(new BeanComparator("datum")));

            return theResult;
        }
    });
}

From source file:edu.duke.cabig.c3pr.dao.HealthcareSiteDao.java

License:BSD License

@SuppressWarnings("unchecked")
public HealthcareSite getByTypeAndCodeFromLocal(String typeName, String code, Boolean isPrimary) {
    if (StringUtils.isEmpty(code)) {
        return null;
    }/* w w  w.j av a 2 s.  c  o  m*/

    Criteria orgCriteria = getHibernateTemplate().getSessionFactory().getCurrentSession()
            .createCriteria(HealthcareSite.class);
    Criteria identifiersAssignedToOrganizationCriteria = orgCriteria
            .createCriteria("identifiersAssignedToOrganization");
    Conjunction conjunction = Restrictions.conjunction();
    conjunction.add(Expression.eq("typeInternal", typeName));
    conjunction.add(Expression.eq("value", code));
    if (isPrimary != null) {
        conjunction.add(Expression.eq("primaryIndicator", isPrimary));
    }
    identifiersAssignedToOrganizationCriteria.add(conjunction);
    return CollectionUtils.firstElement((List<HealthcareSite>) orgCriteria.list());
}

From source file:edu.northwestern.bioinformatics.studycalendar.dao.StudySiteDao.java

License:BSD License

private DetachedCriteria createIntersectionCriteria(Collection<Integer> studyIds, Collection<Integer> siteIds) {
    DetachedCriteria criteria = DetachedCriteria.forClass(StudySite.class);

    Conjunction and = Restrictions.conjunction();
    if (siteIds != null) {
        and.add(MoreRestrictions.in("site.id", siteIds));
    }//w ww . ja  v  a  2s  .  c  o  m
    if (studyIds != null) {
        and.add(MoreRestrictions.in("study.id", studyIds));
    }
    criteria.add(and);
    return criteria;
}

From source file:edu.northwestern.bioinformatics.studycalendar.dao.StudySubjectAssignmentDao.java

License:BSD License

private DetachedCriteria createIntersectionCriteria(Collection<Integer> studyIds, Collection<Integer> siteIds) {
    DetachedCriteria criteria = criteria().createAlias("studySite", "ss");

    Conjunction and = Restrictions.conjunction();
    if (siteIds != null) {
        and.add(MoreRestrictions.in("ss.site.id", siteIds));
    }//w w  w  .j a v a  2 s  .c  o m
    if (studyIds != null) {
        and.add(MoreRestrictions.in("ss.study.id", studyIds));
    }
    criteria.add(and);
    return criteria;
}

From source file:edu.utah.further.core.data.hibernate.query.CriterionBuilderHibernateImpl.java

License:Apache License

/**
 * @param criterion//from w  w w  . j  a v  a  2 s  .c  om
 * @see #visit(edu.utah.further.core.data.search.JunctionCriterionImpl)
 */
public void visitJunction() {
    final SearchType searchType = criterion.getSearchType();
    switch (searchType) {
    case CONJUNCTION: {
        result = Restrictions.conjunction();
        break;
    }

    case DISJUNCTION: {
        result = Restrictions.disjunction();
        break;
    }

    default: {
        throw new BusinessRuleException(unsupportedMessage(searchType));
    }
    }

    // Add junction arguments
    for (final Criterion c : convertedCriteria) {
        ((Junction) result).add(c);
    }
}

From source file:es.sm2.openppm.core.dao.EmployeeDAO.java

License:Open Source License

/**
 * Find Employees where inputed hours is approval
 * //w ww  .j  a va2 s .co  m
 * @param idResourcePools 
 * @param projects
 * @param fullName 
 * @param idJobCategories 
 * @param idPMs 
 * @param idSellers 
 * @param idCategories 
 * @param since
 * @param until
 * @param order 
 * @param nameOrder 
 * @return
 */
@SuppressWarnings("unchecked")
public List<Employee> findInputedInProjects(Integer[] idResourcePools, List<Project> projects, Integer[] idPMs,
        Integer[] idJobCategories, Integer[] idSellers, Integer[] idCategories, String fullName, Date since,
        Date until, String nameOrder, String order, Employee user) {

    Criteria crit = getSession().createCriteria(getPersistentClass())
            .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    // Filter by user
    if (user != null) {
        crit.add(Restrictions.eq(Employee.PERFORMINGORG, user.getPerformingorg()));
    }

    // Aliases 
    //
    crit.createAlias(Employee.TEAMMEMBERS, "tm", CriteriaSpecification.INNER_JOIN)
            .createAlias(Employee.TIMESHEETS, "ts", CriteriaSpecification.INNER_JOIN)
            .createAlias("tm." + Teammember.PROJECTACTIVITY, "pa", CriteriaSpecification.INNER_JOIN)
            .createAlias("pa." + Projectactivity.PROJECT, "p", CriteriaSpecification.LEFT_JOIN)
            .createAlias("p." + Project.EMPLOYEEBYPROJECTMANAGER, "pm", CriteriaSpecification.LEFT_JOIN)
            .createAlias(Employee.RESOURCEPOOL, "rp", CriteriaSpecification.LEFT_JOIN)
            .createAlias(Employee.SELLER, "s", CriteriaSpecification.LEFT_JOIN)
            .createAlias("tm." + Teammember.JOBCATEGORY, "jc", CriteriaSpecification.LEFT_JOIN)
            .createAlias("p." + Project.CATEGORY, "c", CriteriaSpecification.LEFT_JOIN);

    // Teammembers 
    //
    crit.add(Restrictions.eq("tm." + Teammember.STATUS, Constants.RESOURCE_ASSIGNED));

    if (since != null && until != null) {

        crit.add(Restrictions.disjunction().add(Restrictions.between("tm." + Teammember.DATEIN, since, until))
                .add(Restrictions.between("tm." + Teammember.DATEOUT, since, until))
                .add(Restrictions.and(Restrictions.le("tm." + Teammember.DATEIN, since),
                        Restrictions.ge("tm." + Teammember.DATEOUT, until))));
    }

    // Timesheets 
    //
    crit.add(Restrictions.eq("ts." + Timesheet.STATUS, Constants.TIMESTATUS_APP3));

    if (since != null && until != null) {

        crit.add(Restrictions.disjunction().add(Restrictions.between("ts." + Timesheet.INITDATE, since, until))
                .add(Restrictions.between("ts." + Timesheet.ENDDATE, since, until))
                .add(Restrictions.and(Restrictions.le("ts." + Timesheet.INITDATE, since),
                        Restrictions.ge("ts." + Timesheet.ENDDATE, until))));
    }

    // Filters
    //
    Conjunction conjunction = Restrictions.conjunction();

    // Filter by projects
    if (ValidateUtil.isNotNull(projects)) {
        conjunction.add(Restrictions.in("pa." + Projectactivity.PROJECT, projects));
    }
    // Filter by project managers
    if (ValidateUtil.isNotNull(idPMs)) {
        conjunction.add(Restrictions.in("pm." + Employee.IDEMPLOYEE, idPMs));
    }
    // Filter by resourcepools
    if (ValidateUtil.isNotNull(idResourcePools)) {
        conjunction.add(Restrictions.in("rp." + Resourcepool.IDRESOURCEPOOL, idResourcePools));
    }
    // Filter by sellers
    if (ValidateUtil.isNotNull(idSellers)) {
        conjunction.add(Restrictions.in("s." + Seller.IDSELLER, idSellers));
    }
    // Filter by jobcategories
    if (ValidateUtil.isNotNull(idJobCategories)) {
        conjunction.add(Restrictions.in("jc." + Jobcategory.IDJOBCATEGORY, idJobCategories));
    }
    // Filter by categories
    if (ValidateUtil.isNotNull(idCategories)) {
        conjunction.add(Restrictions.in("c." + Category.IDCATEGORY, idCategories));
    }

    crit.add(conjunction);

    // Filter by Full Name
    Criteria contactCrit = crit.createCriteria(Employee.CONTACT);

    if (ValidateUtil.isNotNull(fullName)) {
        contactCrit.add(Restrictions.ilike(Contact.FULLNAME, "%" + fullName + "%"));
    }

    // Apply Order
    Criteria orderCrit = null;

    String alias = StringPool.BLANK;

    if (Project.IDPROJECT.equals(nameOrder)) {

        alias = "pm.";
        orderCrit = crit;
    } else if (Jobcategory.IDJOBCATEGORY.equals(nameOrder)) {
        alias = "jc.";
        orderCrit = crit;
    } else {
        orderCrit = contactCrit;
    }

    if (nameOrder != null) {

        if (Constants.DESCENDENT.equals(order)) {
            orderCrit.addOrder(Order.desc(alias + nameOrder));
        } else {
            orderCrit.addOrder(Order.asc(alias + nameOrder));
        }
    }

    // Calendar base 
    crit.setFetchMode(Employee.CALENDARBASE, FetchMode.JOIN);

    return crit.list();
}