Example usage for org.hibernate.criterion CriteriaSpecification LEFT_JOIN

List of usage examples for org.hibernate.criterion CriteriaSpecification LEFT_JOIN

Introduction

In this page you can find the example usage for org.hibernate.criterion CriteriaSpecification LEFT_JOIN.

Prototype

int LEFT_JOIN

To view the source code for org.hibernate.criterion CriteriaSpecification LEFT_JOIN.

Click Source Link

Document

Specifies joining to an entity based on a left outer join.

Usage

From source file:de.decidr.model.commands.tenant.GetUsersOfTenantCommand.java

License:Apache License

@SuppressWarnings("unchecked")
@Override//from w  w  w  . j a  v a 2  s. c  o  m
public void transactionAllowed(TransactionStartedEvent evt) throws TransactionException {

    PaginatingCriteria c = new PaginatingCriteria(User.class, "u", evt.getSession());

    String rootAlias = c.getAlias();

    // Create criterion "user is a member of the tenant"
    DetachedCriteria memberRel = DetachedCriteria.forClass(UserIsMemberOfTenant.class, "memberRel");
    memberRel.add(Property.forName("memberRel.user.id").eqProperty(rootAlias + ".id"))
            .add(Property.forName("memberRel.tenant.id").eq(getTenantId()));

    // Create criterion "user is the administrator of the tenant"
    DetachedCriteria adminRel = DetachedCriteria.forClass(Tenant.class, "adminTenant");
    adminRel.add(Property.forName("adminTenant.id").eq(getTenantId()))
            .add(Property.forName("adminTenant.admin.id").eqProperty(rootAlias + ".id"));

    /*
     * 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 "*"
     */
    Projection existsSubqueryProjection = Projections.sqlProjection("*", new String[0], new Type[0]);
    memberRel.setProjection(existsSubqueryProjection);
    adminRel.setProjection(existsSubqueryProjection);

    c.add(Restrictions.or(Subqueries.exists(memberRel), Subqueries.exists(adminRel)));

    // preload user profiles - no lazy loading desired
    c.createCriteria("userProfile", CriteriaSpecification.LEFT_JOIN);
    c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);

    if (paginator != null) {
        paginator.apply(c);
    }
    result = c.list();
}

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

License:Apache License

@SuppressWarnings("unchecked")
@Override//from   w  w w  .j  ava2 s. c  om
public void transactionAllowed(TransactionStartedEvent evt) throws TransactionException {

    PaginatingCriteria c = new PaginatingCriteria(User.class, evt.getSession());

    c.createCriteria("userProfile", CriteriaSpecification.LEFT_JOIN);

    Filters.apply(c, filters, paginator);

    result = c.list();
}

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

License:Apache License

@Override
public void transactionAllowed(TransactionStartedEvent evt) throws TransactionException {
    passwordCorrect = false;//from  w  ww . ja v a  2 s.co m

    // find the existing user
    Criteria crit = evt.getSession().createCriteria(User.class, "u");
    crit.createAlias("userProfile", "p", CriteriaSpecification.LEFT_JOIN);
    // the DecidR username criteria do not allow non-alphanumeric characters
    // in usernames, so the case user1.username = user2.email should not
    // occur. Otherwise, uniqueResult() will throw a runtime exception.
    crit.add(Restrictions.or(Restrictions.eq("u.email", emailOrUsername),
            Restrictions.eq("p.username", emailOrUsername)));

    User existingUser = (User) crit.uniqueResult();

    if (existingUser == null) {
        // user account not found
        throw new EntityNotFoundException(User.class);
    }

    String hash = Password.getHash(passwordPlaintext, existingUser.getUserProfile().getPasswordSalt());

    // is the password correct?
    passwordCorrect = hash.equals(existingUser.getUserProfile().getPasswordHash());
    user = existingUser;

    // log the login to the database
    Login thisLogin = new Login();
    thisLogin.setLoginDate(DecidrGlobals.getTime().getTime());
    thisLogin.setSuccess(passwordCorrect);
    thisLogin.setUser(existingUser);
    evt.getSession().save(thisLogin);
}

From source file:de.decidr.model.commands.workflowmodel.GetWorkflowInstancesCommand.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/*from  www  .  ja v  a2s. c om*/
public void transactionAllowed(TransactionStartedEvent evt) throws TransactionException {
    result = null;

    WorkflowModel model = fetchWorkflowModel(evt.getSession());

    PaginatingCriteria crit = new PaginatingCriteria(WorkflowInstance.class, evt.getSession());

    crit.createCriteria("deployedWorkflowModel", "dwm", CriteriaSpecification.LEFT_JOIN)
            .add(Restrictions.eq("dwm.originalWorkflowModel", model));

    if (paginator != null) {
        paginator.apply(crit);
    }

    List<WorkflowInstance> instances = crit.list();
    /*
     * make sure the needed properties are retrieved.
     */
    for (WorkflowInstance instance : instances) {
        instance.getId();
        instance.getCompletedDate();
        instance.getStartedDate();
        instance.getDeployedWorkflowModel().getName();
        instance.getDeployedWorkflowModel().getDescription();
        instance.getDeployedWorkflowModel().getDeployDate();
    }

    result = instances;
}

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

License:Open Source License

/**
 * Search Contacts by filter/*from w w w.j a  va2 s  .  c  om*/
 * @param resourcepools
  * @param fullName
  * @param fileAs
  * @param performingorg
  * @param company
  * @param skills
  *@param jobcategories @return
 */
@SuppressWarnings("unchecked")
public List<Contact> searchByFilter(String fullName, String fileAs, Performingorg performingorg,
        Company company, List<Resourcepool> resourcepools, List<Skill> skills,
        List<Jobcategory> jobcategories) {

    Contact example = new Contact();
    example.setFileAs(fileAs);
    example.setFullName(fullName);

    Criteria crit = getSession().createCriteria(getPersistentClass())
            .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)
            .add(Example.create(example).ignoreCase().enableLike(MatchMode.ANYWHERE))
            .add(Restrictions.or(Restrictions.isNull(Contact.DISABLE), Restrictions.ne(Contact.DISABLE, true)));

    // Company
    //
    crit.createCriteria(Contact.COMPANY).add(Restrictions.idEq(company.getIdCompany()))
            .add(Restrictions.or(Restrictions.isNull(Company.DISABLE), Restrictions.ne(Company.DISABLE, true)));

    // Employee
    Criteria critEmployee = crit.createCriteria(Contact.EMPLOYEES, CriteriaSpecification.LEFT_JOIN);

    if (performingorg != null && performingorg.getIdPerfOrg() != null && performingorg.getIdPerfOrg() != -1) {

        critEmployee.createCriteria(Employee.PERFORMINGORG)
                .add(Restrictions.idEq(performingorg.getIdPerfOrg()));
    }

    if (ValidateUtil.isNotNull(resourcepools)) {
        critEmployee.add(Restrictions.in(Employee.RESOURCEPOOL, resourcepools));
    }

    if (ValidateUtil.isNotNull(skills)) {
        critEmployee.createCriteria(Employee.SKILLSEMPLOYEES)
                .add(Restrictions.in(Skillsemployee.SKILL, skills));
    }

    if (ValidateUtil.isNotNull(jobcategories)) {
        critEmployee.createCriteria(Employee.JOBCATEMPLOYEES)
                .add(Restrictions.in(Jobcatemployee.JOBCATEGORY, jobcategories));
    }

    return crit.list();
}

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  va  2 s .c om
 * @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();
}

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

License:Open Source License

/**
 * Find milestones filter by projects and milestone type and dates
 * //from w  w  w  .ja  va 2s .  co  m
 * @param projects
 * @param milestonetype 
 * @param milestonecategory 
 * @param until 
 * @param since 
 * @param milestonePending
 * @param property
 * @param order
 * @param joins
 * @return
 */
@SuppressWarnings("unchecked")
public List<Milestones> filter(List<Project> projects, Milestonetype milestonetype,
        Milestonecategory milestonecategory, Date since, Date until, String milestonePending, String property,
        String order, List<String> joins) {

    List<Milestones> list = new ArrayList<Milestones>();

    if (ValidateUtil.isNotNull(projects)) {

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

        // Filter dates
        //
        if (since != null & until != null) {

            crit.add(Restrictions.disjunction()
                    .add(Restrictions.conjunction().add(Restrictions.isNotNull(Milestones.ACHIEVED))
                            .add(Restrictions.between(Milestones.ACHIEVED, since, until)))
                    .add(Restrictions.conjunction().add(Restrictions.isNotNull(Milestones.ESTIMATEDDATE))
                            .add(Restrictions.between(Milestones.ESTIMATEDDATE, since, until)))
                    .add(Restrictions.conjunction().add(Restrictions.isNotNull(Milestones.PLANNED))
                            .add(Restrictions.between(Milestones.PLANNED, since, until))));
        } else if (since != null) {

            crit.add(Restrictions.disjunction()
                    .add(Restrictions.conjunction().add(Restrictions.isNotNull(Milestones.ACHIEVED))
                            .add(Restrictions.ge(Milestones.ACHIEVED, since)))
                    .add(Restrictions.conjunction().add(Restrictions.isNotNull(Milestones.ESTIMATEDDATE))
                            .add(Restrictions.ge(Milestones.ESTIMATEDDATE, since)))
                    .add(Restrictions.conjunction().add(Restrictions.isNotNull(Milestones.PLANNED))
                            .add(Restrictions.ge(Milestones.PLANNED, since))));
        } else if (until != null) {

            crit.add(Restrictions.disjunction()
                    .add(Restrictions.conjunction().add(Restrictions.isNotNull(Milestones.ACHIEVED))
                            .add(Restrictions.le(Milestones.ACHIEVED, until)))
                    .add(Restrictions.conjunction().add(Restrictions.isNotNull(Milestones.ESTIMATEDDATE))
                            .add(Restrictions.le(Milestones.ESTIMATEDDATE, until)))
                    .add(Restrictions.conjunction().add(Restrictions.isNotNull(Milestones.PLANNED))
                            .add(Restrictions.le(Milestones.PLANNED, until))));
        }

        // Filter by projects
        //
        crit.add(Restrictions.in(Milestones.PROJECT, projects));

        // Filter by milestone type
        //
        if (milestonetype != null) {
            crit.add(Restrictions.eq(Milestones.MILESTONETYPE, milestonetype));
        }

        // Filter by milestone category
        //
        if (milestonecategory != null) {
            crit.add(Restrictions.eq(Milestones.MILESTONECATEGORY, milestonecategory));
        }

        // Filter by pendings 
        //
        if (MilestonePending.YES.name().equals(milestonePending)) {
            crit.add(Restrictions.isNull(Milestones.ACHIEVED));
        } else if (MilestonePending.NO.name().equals(milestonePending)) {
            crit.add(Restrictions.isNotNull(Milestones.ACHIEVED));
        }

        // Left join milestone type for null relation
        crit.createCriteria(Milestones.MILESTONETYPE, CriteriaSpecification.LEFT_JOIN);

        // Joins
        addJoins(crit, joins);

        // Orders
        addOrder(crit, property, order);

        list = crit.list();
    }

    return list;
}

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

License:Open Source License

/**
 * Calculate Fte for inputed hours in project
 * /*from w  w  w  .j  ava  2s  .  co  m*/
 * @param project
 * @param member
 * @param firstWeekDay
 * @param lastWeekDay
 * @return
 */
public double getHoursResource(Project project, Employee member, Date firstWeekDay, Date lastWeekDay) {

    ProjectionList proList = Projections.projectionList();
    proList.add(Projections.sum(Timesheet.HOURSDAY1));
    proList.add(Projections.sum(Timesheet.HOURSDAY2));
    proList.add(Projections.sum(Timesheet.HOURSDAY3));
    proList.add(Projections.sum(Timesheet.HOURSDAY4));
    proList.add(Projections.sum(Timesheet.HOURSDAY5));
    proList.add(Projections.sum(Timesheet.HOURSDAY6));
    proList.add(Projections.sum(Timesheet.HOURSDAY7));

    Criteria crit = getSession().createCriteria(getPersistentClass()).setProjection(proList)
            .add(Restrictions.eq(Timesheet.STATUS, Constants.TIMESTATUS_APP3))
            .add(Restrictions.eq(Timesheet.EMPLOYEE, member));

    if (firstWeekDay != null && lastWeekDay != null) {

        crit.add(Restrictions.eq(Timesheet.INITDATE, firstWeekDay))
                .add(Restrictions.eq(Timesheet.ENDDATE, lastWeekDay));
    }

    // Aliases 
    //
    crit.createAlias(Timesheet.PROJECTACTIVITY, "pa", CriteriaSpecification.LEFT_JOIN);

    // Projects or operations
    crit.add(Restrictions.disjunction().add(Restrictions.isNotNull(Timesheet.OPERATION))
            .add(Restrictions.eq("pa." + Projectactivity.PROJECT, project)));

    Object[] hoursList = (Object[]) crit.uniqueResult();

    double hours = 0;

    if (hoursList != null) {
        hours += (hoursList[0] == null ? 0 : (Double) hoursList[0]);
        hours += (hoursList[1] == null ? 0 : (Double) hoursList[1]);
        hours += (hoursList[2] == null ? 0 : (Double) hoursList[2]);
        hours += (hoursList[3] == null ? 0 : (Double) hoursList[3]);
        hours += (hoursList[4] == null ? 0 : (Double) hoursList[4]);
        hours += (hoursList[5] == null ? 0 : (Double) hoursList[5]);
        hours += (hoursList[6] == null ? 0 : (Double) hoursList[6]);
    }

    return hours;
}

From source file:es.tid.fiware.rss.dao.impl.ServiceDeploymentDaoImpl.java

License:Open Source License

@Override
public List<BmServiceDeployment> getDeploymentsbyServiceId(final long serviceId) {

    Criteria criteria = getSession().createCriteria(BmServiceDeployment.class);
    criteria.createAlias("bmService", "bmService", CriteriaSpecification.LEFT_JOIN);
    criteria.add(Restrictions.eq("bmService.nuServiceId", serviceId));
    List<BmServiceDeployment> result = criteria.list();
    return result;
}

From source file:gov.nih.nci.caintegrator.domain.annotation.service.AnnotationManagerImpl.java

License:BSD License

public Map<String, Collection<GeneBiomarker>> getGenesForReporters(AnnotationCriteria annotationCriteria) {

    HashMap<String, Collection<GeneBiomarker>> reporterMap = new HashMap<String, Collection<GeneBiomarker>>();
    ArrayPlatformType arrayPlatformType = annotationCriteria.getArrayPlatformType();
    Collection<String> reporters = annotationCriteria.getReporterIds();

    if (arrayPlatformType == null) {
        throw new RuntimeException("Array Platform type cannot be null");
    }//from w ww .  ja v a 2s.  c  o  m
    if (reporters == null || reporters.isEmpty()) {
        throw new RuntimeException("Reporter list must not be empty");
    }

    Session currentSession = sessionFactory.getCurrentSession();

    List<GeneExprReporter> reporterList = new ArrayList<GeneExprReporter>();
    if (reporters.size() > 1000) {
        for (int i = 0; i < ((reporters.size() / 1000) + 1); i++) {
            Criteria criteria = currentSession.createCriteria(GeneExprReporter.class);
            criteria.createAlias("geneBiomarkerCollection", "gene", CriteriaSpecification.LEFT_JOIN);

            int size;
            if (i == (reporters.size() / 1000)) {
                size = reporters.size() % 1000;
            } else {
                size = 1000;
            }
            String[] tempArray = new String[size];
            System.arraycopy(reporters.toArray(), i * 1000, tempArray, 0, size);
            Collection tempList = new ArrayList();
            Collections.addAll(tempList, tempArray);
            criteria.add(Restrictions.in("name", tempList));
            reporterList.addAll(criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list());
        }
    } else {
        Criteria criteria = currentSession.createCriteria(GeneExprReporter.class);
        criteria.createAlias("geneBiomarkerCollection", "gene", CriteriaSpecification.LEFT_JOIN);
        criteria.add(Restrictions.in("name", reporters));
        reporterList = criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
    }

    for (GeneExprReporter reporter : reporterList) {
        reporterMap.put(reporter.getName(), reporter.getGeneBiomarkerCollection());
    }

    return reporterMap;
}