Example usage for org.hibernate.criterion CriteriaSpecification INNER_JOIN

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

Introduction

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

Prototype

int INNER_JOIN

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

Click Source Link

Document

Specifies joining to an entity based on an inner join.

Usage

From source file:com.amalto.core.storage.hibernate.EntityFinder.java

License:Open Source License

/**
 * Starting from <code>wrapper</code>, goes up the containment tree using references introspection in metadata.
 * @param wrapper A {@link Wrapper} instance (so an object managed by {@link HibernateStorage}.
 * @param storage A {@link HibernateStorage} instance. It will be used to compute references from the internal
 *                data model.//  w ww.j  a va2 s.  c om
 * @param session A Hibernate {@link Session}.
 * @return The top level (aka the Wrapper instance that represent a MDM entity).
 */
public static Wrapper findEntity(Wrapper wrapper, HibernateStorage storage, Session session) {
    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    if (!(contextClassLoader instanceof StorageClassLoader)) {
        throw new IllegalStateException("Expects method to be called in the context of a storage operation.");
    }
    StorageClassLoader classLoader = (StorageClassLoader) contextClassLoader;
    ComplexTypeMetadata wrapperType = classLoader.getTypeFromClass(wrapper.getClass());
    if (wrapperType == null) {
        throw new IllegalArgumentException(
                "Wrapper '" + wrapper.getClass().getName() + "' isn't known in current storage.");
    }
    if (wrapperType.isInstantiable()) {
        return wrapper;
    }
    InboundReferences incomingReferences = new InboundReferences(wrapperType);
    InternalRepository internalRepository = storage.getTypeEnhancer();
    Set<ReferenceFieldMetadata> references = internalRepository.getInternalRepository()
            .accept(incomingReferences);
    if (references.isEmpty()) {
        throw new IllegalStateException("Cannot find container type for '" + wrapperType.getName() + "'.");
    }
    String keyFieldName = wrapperType.getKeyFields().iterator().next().getName();
    Object id = wrapper.get(keyFieldName);
    for (ReferenceFieldMetadata reference : references) {
        ComplexTypeMetadata containingType = reference.getContainingType();
        Class<? extends Wrapper> clazz = classLoader.getClassFromType(containingType);
        Criteria criteria = session.createCriteria(clazz, "a0"); //$NON-NLS-1$
        criteria.createAlias("a0." + reference.getName(), "a1", CriteriaSpecification.INNER_JOIN); //$NON-NLS-1$
        criteria.add(Restrictions.eq("a1." + keyFieldName, id)); //$NON-NLS-1$
        List list = criteria.list();
        if (!list.isEmpty()) {
            Wrapper container = (Wrapper) list.get(0);
            if (list.size() > 1) {
                Object previousItem = list.get(0);
                for (int i = 1; i < list.size(); i++) {
                    Object currentItem = list.get(i);
                    if (!previousItem.equals(currentItem)) {
                        throw new IllegalStateException("Expected contained instance to have only one owner.");
                    }
                    previousItem = currentItem;
                }
            }
            return findEntity(container, storage, session);
        }
    }
    return null;
}

From source file:com.cimmyt.model.dao.impl.LabStudyDAOImpl.java

License:Apache License

private void addCriteria(DetachedCriteria criteria, List<DsSearchParam> params,
        boolean useSampleDetailFilters) {
    boolean hasAND = false;
    boolean hasOR = false;

    List<DsSearchParam> paramList = new ArrayList<DsSearchParam>(params);

    criteria.createAlias("project", VALUE_PROJECT)
            .createAlias("investigatorid", "investigator", CriteriaSpecification.LEFT_JOIN)
            .createAlias("season", "season", CriteriaSpecification.LEFT_JOIN)
            .createAlias("location", "location", CriteriaSpecification.LEFT_JOIN);

    if (useSampleDetailFilters)
        criteria.createAlias("sampleDetailCollection", VALUE_SAMPLE, CriteriaSpecification.INNER_JOIN);

    //separates 'OR' from other operators, to use in disjunction
    List<DsSearchParam> orParams = new ArrayList<DsSearchParam>();
    for (DsSearchParam p : paramList) {
        if (p.getOperator().equals(TypeCondition.OR)) {
            orParams.add(p);/*from w ww  . ja v a2  s.c  o  m*/
        }
    }
    paramList.removeAll(orParams);

    String qualifiedParam = null;
    Conjunction conjunction = Restrictions.conjunction();

    for (DsSearchParam param : paramList) {
        hasAND = true;

        qualifiedParam = param.getQualifier();
        DataType dataType = OperatorImp.getType(param.getElement(), param.getQualifier());
        Operator condition = OperatorImp.valueOf(param.getCondition());

        addDynamicCriterion(conjunction, condition, dataType, qualifiedParam, param.getValue());
    }

    Disjunction disjunction = Restrictions.disjunction();
    for (DsSearchParam param : orParams) {
        hasOR = true;

        qualifiedParam = param.getQualifier();
        DataType dataType = OperatorImp.getType(param.getElement(), param.getQualifier());
        Operator condition = OperatorImp.valueOf(param.getCondition());

        addDynamicCriterion(disjunction, condition, dataType, qualifiedParam, param.getValue());
    }

    if (hasAND) {
        if (hasOR) {
            criteria.add(Restrictions.or(conjunction, disjunction));
        } else {
            criteria.add(conjunction);
        }
    } else if (hasOR) {
        criteria.add(disjunction);
    }
}

From source file:com.ihsolution.hqipo.dao.utils.QueryHelper.java

License:Open Source License

protected String createAliases(String field) {
    String[] fStrs = field.split("\\.");
    String tmpField = "", fetchModeValue = "";
    int len = fStrs.length;

    if (len > 1) {
        for (int i = 0; len - i != 1; i++) {
            if (i == 0) {
                if (!aliases.contains(fStrs[i])) {
                    if (this.dto.getJoinTypes().containsKey(fStrs[i])) {

                        fetchModeValue = dto.getJoinTypes().get(fStrs[i]);
                        logger.info(fStrs[i] + "=" + fetchModeValue);
                        //FetchMode fmode = null;
                        int joinType = 0;
                        if (fetchModeValue.equals("left_join"))
                            joinType = CriteriaSpecification.LEFT_JOIN;//FetchMode.JOIN;
                        else if (fetchModeValue.equals("inner_join"))
                            joinType = CriteriaSpecification.INNER_JOIN;//.FetchMode.EAGER;
                        else
                            joinType = CriteriaSpecification.INNER_JOIN;//.FetchMode.EAGER;

                        detCriteria.createAlias(fStrs[i], fStrs[i], joinType);
                    } else {
                        detCriteria.createAlias(fStrs[i], fStrs[i]);
                    }//  w w w  .  j  a va2 s  .  c  om
                    aliases.add(fStrs[i]);
                }
            } else {
                if (!aliases.contains(fStrs[i])) {
                    String str = fStrs[i - 1] + "." + fStrs[i];
                    detCriteria.createAlias(str, fStrs[i]);
                    aliases.add(fStrs[i]);
                }
            }
        }
        tmpField = fStrs[len - 2] + "." + fStrs[len - 1];
    } else
        tmpField = field;

    return tmpField;
}

From source file:com.mg.framework.support.orm.CriteriaHibernateImpl.java

License:Open Source License

protected static int convertJoinModeToHibernate(JoinType joinType) {
    switch (joinType) {
    case FULL_JOIN:
        return CriteriaSpecification.FULL_JOIN;
    case INNER_JOIN:
        return CriteriaSpecification.INNER_JOIN;
    case LEFT_JOIN:
        return CriteriaSpecification.LEFT_JOIN;
    default://from  w  w  w. j  a  v  a 2 s  .  co  m
        throw new IllegalArgumentException();
    }
}

From source file:com.ponysdk.hibernate.query.decorator.AbstractCriteriaDecorator.java

License:Apache License

@SuppressWarnings("rawtypes")
@Override/*from  w w w .  jav a2 s  .co  m*/
public void render(final CriteriaContext context) {
    final Criterion field = context.getCriterion();
    Criteria criteria = context.getOrderingCriteria();

    final List<String> propertyNamePath = Arrays.asList(field.getPojoProperty().split(REGEX_SPLIT));
    final Iterator<String> iter = propertyNamePath.iterator();
    String key = null;
    String associationPath = null;
    if (propertyNamePath.size() == 1) {
        associationPath = iter.next();
    } else
        while (iter.hasNext()) {
            key = iter.next();
            if (associationPath == null) {
                associationPath = new String(key);
            } else {
                associationPath += "." + key;
            }
            if (iter.hasNext()) {
                criteria = criteria.createCriteria(associationPath, key, CriteriaSpecification.INNER_JOIN);
                associationPath = new String(key);
            }
        }

    final T value = getObjectValue(field);
    ComparatorType comparator = field.getComparator();

    if (value != null) {
        if (value.toString().contains("%")) {
            comparator = ComparatorType.LIKE;
        }
    }

    if (field.getValue() != null || field.getComparator() == ComparatorType.IS_NULL
            || field.getComparator() == ComparatorType.IS_NOT_NULL) {

        switch (comparator) {
        case EQ:
            criteria.add(Restrictions.eq(associationPath, value));
            break;
        case GE:
            criteria.add(Restrictions.ge(associationPath, value));
            break;
        case GT:
            criteria.add(Restrictions.gt(associationPath, value));
            break;
        case LE:
            criteria.add(Restrictions.le(associationPath, value));
            break;
        case LT:
            criteria.add(Restrictions.lt(associationPath, value));
            break;
        case NE:
            criteria.add(Restrictions.ne(associationPath, value));
            break;
        case LIKE:
            criteria.add(Restrictions.ilike(associationPath, value));
            break;
        case IS_NULL:
            criteria.add(Restrictions.isNull(associationPath));
            break;
        case IS_NOT_NULL:
            criteria.add(Restrictions.isNotNull(associationPath));
            break;
        case IN:
            if (value instanceof Collection) {
                criteria.add(Restrictions.in(associationPath, (Collection) value));
            } else if (value instanceof Object[]) {
                criteria.add(Restrictions.in(associationPath, (Object[]) value));
            } else {
                log.warn("Type not allowed for IN clause: " + value.getClass() + ", value: " + value);
            }
            break;

        default:
            log.warn("Restriction not supported: " + comparator);
            break;
        }
    }

    switch (field.getSortingType()) {
    case ASCENDING:
        criteria.addOrder(Order.asc(associationPath));
        break;
    case DESCENDING:
        criteria.addOrder(Order.desc(associationPath));
        break;
    case NONE:
        break;
    }

}

From source file:com.ut.tekir.contact.ContactBrowseBean.java

License:LGPL

@Override
public DetachedCriteria buildCriteria() {
    DetachedCriteria crit = DetachedCriteria.forClass(Contact.class);

    crit.setProjection(Projections.distinct(Projections.projectionList().add(Projections.property("id"), "id")
            .add(Projections.property("code"), "code").add(Projections.property("name"), "name")
            .add(Projections.property("fullname"), "fullname").add(Projections.property("ssn"), "ssn")
            .add(Projections.property("company"), "company").add(Projections.property("taxNumber"), "taxNumber")
            .add(Projections.property("taxOffice"), "taxOffice").add(Projections.property("title"), "title")
            .add(Projections.property("representative"), "representative")
            .add(Projections.property("info"), "info").add(Projections.property("exCode1"), "exCode1")
            .add(Projections.property("exCode2"), "exCode2").add(Projections.property("allType"), "allType")
            .add(Projections.property("customerType"), "customerType")
            .add(Projections.property("providerType"), "providerType")
            .add(Projections.property("agentType"), "agentType")
            .add(Projections.property("personnelType"), "personnelType")
            .add(Projections.property("branchType"), "branchType")
            .add(Projections.property("contactType"), "contactType")
            .add(Projections.property("bankType"), "bankType")
            .add(Projections.property("relatedType"), "relatedType")
            .add(Projections.property("foundationType"), "foundationType")));

    crit.setResultTransformer(Transformers.aliasToBean(ContactModel.class));

    if (filterModel.getCode() != null && filterModel.getCode().length() > 0) {
        crit.add(Restrictions.ilike("this.code", filterModel.getCode(), MatchMode.START));
    }//  w w w  .j a v  a  2  s . co  m

    if (filterModel.getFullname() != null && filterModel.getFullname().length() > 0) {
        crit.add(Restrictions.ilike("this.fullname", filterModel.getFullname(), MatchMode.ANYWHERE));
    }

    if (filterModel.getCompany() != null && filterModel.getCompany().length() > 0) {
        crit.add(Restrictions.ilike("this.company", filterModel.getCompany(), MatchMode.START));
    }

    if (filterModel.getSsn() != null && filterModel.getSsn().length() > 0) {
        crit.add(Restrictions.ilike("this.ssn", filterModel.getSsn(), MatchMode.START));
    }

    if (filterModel.getTaxNumber() != null && filterModel.getTaxNumber().length() > 0) {
        crit.add(Restrictions.ilike("this.taxNumber", filterModel.getTaxNumber(), MatchMode.START));
    }

    if (filterModel.getRepresentative() != null && filterModel.getRepresentative().length() > 0) {
        crit.add(Restrictions.ilike("this.representative", filterModel.getRepresentative(), MatchMode.START));
    }

    if (filterModel.getExCode1() != null && filterModel.getExCode1().length() > 0) {
        crit.add(Restrictions.ilike("this.exCode1", filterModel.getExCode1(), MatchMode.START));
    }

    if (filterModel.getExCode2() != null && filterModel.getExCode2().length() > 0) {
        crit.add(Restrictions.ilike("this.exCode2", filterModel.getExCode2(), MatchMode.START));
    }

    if (filterModel.getCategory() != null) {
        crit.add(Restrictions.eq("this.category", filterModel.getCategory()));
    }

    if (filterModel.getOrganization() != null) {
        crit.add(Restrictions.eq("this.organization", filterModel.getOrganization()));
    }

    if (filterModel.getCompanyType() != null && !filterModel.getCompanyType().equals("All")) {
        if (filterModel.getCompanyType().equals("Person")) {
            crit.add(Restrictions.eq("this.person", Boolean.TRUE));
        } else
            crit.add(Restrictions.eq("this.person", Boolean.FALSE));
    }

    if (filterModel.getType() != null && filterModel.getType() != ContactType.All) {
        crit.add(Restrictions.eq("this." + filterModel.getType().toString().toLowerCase() + "Type",
                Boolean.TRUE));
    }

    if (filterModel.getCountry() != null) {
        crit.createAlias("this.addressList", "addressList", CriteriaSpecification.INNER_JOIN);
        crit.add(Restrictions.eq("addressList.address.country", filterModel.getCountry()));

        if (filterModel.getCity1() != null) {
            crit.add(Restrictions.eq("addressList.city", filterModel.getCity1()));
        }
    }

    //FIXME: bu kontrol nasl olmal?
    if (hasRegionRestriction()) {
        if (activeUser.getContact() != null && activeUser.getContact().getOrganization() != null
                && activeUser.getContact().getOrganization() != null) {

            crit.add(Restrictions.or(
                    Restrictions.eq("this.organization.id", activeUser.getContact().getOrganization().getId()),
                    Restrictions.eq("this.isPublic", Boolean.TRUE)));
        }
    }
    crit.addOrder(Order.desc("this.code"));

    return crit;
}

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

License:Apache License

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

    String hql = "select t.id from Tenant t where t.id  = :tenantId";
    Boolean tenantExists = evt.getSession().createQuery(hql).setLong("tenantId", getTenantId())
            .uniqueResult() != null;

    if (!tenantExists) {
        throw new EntityNotFoundException(Tenant.class, getTenantId());
    }

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

    Criteria c2;

    // create criteria 2nd level and project to name
    c2 = c.createCriteria("deployedWorkflowModel", CriteriaSpecification.INNER_JOIN);

    // create criteria 3rd level and project to name
    c2.createCriteria("tenant", CriteriaSpecification.INNER_JOIN).add(Restrictions.idEq(getTenantId()));

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

    c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);

    result = c.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 av a2 s . com*/
 * @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:grails.orm.HibernateCriteriaBuilder.java

License:Apache License

@SuppressWarnings("rawtypes")
@Override/*from  w w w.  j  a va 2 s. c o m*/
public Object invokeMethod(String name, Object obj) {
    Object[] args = obj.getClass().isArray() ? (Object[]) obj : new Object[] { obj };

    if (paginationEnabledList && SET_RESULT_TRANSFORMER_CALL.equals(name) && args.length == 1
            && args[0] instanceof ResultTransformer) {
        resultTransformer = (ResultTransformer) args[0];
        return null;
    }

    if (isCriteriaConstructionMethod(name, args)) {
        if (criteria != null) {
            throwRuntimeException(new IllegalArgumentException("call to [" + name + "] not supported here"));
        }

        if (name.equals(GET_CALL)) {
            uniqueResult = true;
        } else if (name.equals(SCROLL_CALL)) {
            scroll = true;
        } else if (name.equals(COUNT_CALL)) {
            count = true;
        } else if (name.equals(LIST_DISTINCT_CALL)) {
            resultTransformer = CriteriaSpecification.DISTINCT_ROOT_ENTITY;
        }

        createCriteriaInstance();

        // Check for pagination params
        if (name.equals(LIST_CALL) && args.length == 2) {
            paginationEnabledList = true;
            orderEntries = new ArrayList<Order>();
            invokeClosureNode(args[1]);
        } else {
            invokeClosureNode(args[0]);
        }

        if (resultTransformer != null) {
            criteria.setResultTransformer(resultTransformer);
        }
        Object result;
        if (!uniqueResult) {
            if (scroll) {
                result = criteria.scroll();
            } else if (count) {
                criteria.setProjection(Projections.rowCount());
                result = criteria.uniqueResult();
            } else if (paginationEnabledList) {
                // Calculate how many results there are in total. This has been
                // moved to before the 'list()' invocation to avoid any "ORDER
                // BY" clause added by 'populateArgumentsForCriteria()', otherwise
                // an exception is thrown for non-string sort fields (GRAILS-2690).
                criteria.setFirstResult(0);
                criteria.setMaxResults(Integer.MAX_VALUE);
                criteria.setProjection(Projections.rowCount());
                int totalCount = ((Number) criteria.uniqueResult()).intValue();

                // Restore the previous projection, add settings for the pagination parameters,
                // and then execute the query.
                if (projectionList != null && projectionList.getLength() > 0) {
                    criteria.setProjection(projectionList);
                } else {
                    criteria.setProjection(null);
                }
                for (Order orderEntry : orderEntries) {
                    criteria.addOrder(orderEntry);
                }
                if (resultTransformer == null) {
                    criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
                } else if (paginationEnabledList) {
                    // relevant to GRAILS-5692
                    criteria.setResultTransformer(resultTransformer);
                }
                // GRAILS-7324 look if we already have association to sort by
                Map argMap = (Map) args[0];
                final String sort = (String) argMap.get(GrailsHibernateUtil.ARGUMENT_SORT);
                if (sort != null) {
                    boolean ignoreCase = true;
                    Object caseArg = argMap.get(GrailsHibernateUtil.ARGUMENT_IGNORE_CASE);
                    if (caseArg instanceof Boolean) {
                        ignoreCase = (Boolean) caseArg;
                    }
                    final String orderParam = (String) argMap.get(GrailsHibernateUtil.ARGUMENT_ORDER);
                    final String order = GrailsHibernateUtil.ORDER_DESC.equalsIgnoreCase(orderParam)
                            ? GrailsHibernateUtil.ORDER_DESC
                            : GrailsHibernateUtil.ORDER_ASC;
                    int lastPropertyPos = sort.lastIndexOf('.');
                    String associationForOrdering = lastPropertyPos >= 0 ? sort.substring(0, lastPropertyPos)
                            : null;
                    if (associationForOrdering != null && aliasMap.containsKey(associationForOrdering)) {
                        addOrder(criteria, aliasMap.get(associationForOrdering) + "."
                                + sort.substring(lastPropertyPos + 1), order, ignoreCase);
                        // remove sort from arguments map to exclude from default processing.
                        @SuppressWarnings("unchecked")
                        Map argMap2 = new HashMap(argMap);
                        argMap2.remove(GrailsHibernateUtil.ARGUMENT_SORT);
                        argMap = argMap2;
                    }
                }
                GrailsHibernateUtil.populateArgumentsForCriteria(grailsApplication, targetClass, criteria,
                        argMap);
                PagedResultList pagedRes = new PagedResultList(criteria.list());

                // Updated the paged results with the total number of records calculated previously.
                pagedRes.setTotalCount(totalCount);
                result = pagedRes;
            } else {
                result = criteria.list();
            }
        } else {
            result = GrailsHibernateUtil.unwrapIfProxy(criteria.uniqueResult());
        }
        if (!participate) {
            hibernateSession.close();
        }
        return result;
    }

    if (criteria == null)
        createCriteriaInstance();

    MetaMethod metaMethod = getMetaClass().getMetaMethod(name, args);
    if (metaMethod != null) {
        return metaMethod.invoke(this, args);
    }

    metaMethod = criteriaMetaClass.getMetaMethod(name, args);
    if (metaMethod != null) {
        return metaMethod.invoke(criteria, args);
    }
    metaMethod = criteriaMetaClass.getMetaMethod(GrailsClassUtils.getSetterName(name), args);
    if (metaMethod != null) {
        return metaMethod.invoke(criteria, args);
    }

    if (isAssociationQueryMethod(args) || isAssociationQueryWithJoinSpecificationMethod(args)) {
        final boolean hasMoreThanOneArg = args.length > 1;
        Object callable = hasMoreThanOneArg ? args[1] : args[0];
        int joinType = hasMoreThanOneArg ? (Integer) args[0] : CriteriaSpecification.INNER_JOIN;

        if (name.equals(AND) || name.equals(OR) || name.equals(NOT)) {
            if (criteria == null) {
                throwRuntimeException(
                        new IllegalArgumentException("call to [" + name + "] not supported here"));
            }

            logicalExpressionStack.add(new LogicalExpression(name));
            invokeClosureNode(callable);

            LogicalExpression logicalExpression = logicalExpressionStack
                    .remove(logicalExpressionStack.size() - 1);
            addToCriteria(logicalExpression.toCriterion());

            return name;
        }

        if (name.equals(PROJECTIONS) && args.length == 1 && (args[0] instanceof Closure)) {
            if (criteria == null) {
                throwRuntimeException(
                        new IllegalArgumentException("call to [" + name + "] not supported here"));
            }

            projectionList = Projections.projectionList();
            invokeClosureNode(callable);

            if (projectionList != null && projectionList.getLength() > 0) {
                criteria.setProjection(projectionList);
            }

            return name;
        }

        final PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(targetClass, name);
        if (pd != null && pd.getReadMethod() != null) {
            ClassMetadata meta = sessionFactory.getClassMetadata(targetClass);
            Type type = meta.getPropertyType(name);
            if (type.isAssociationType()) {
                String otherSideEntityName = ((AssociationType) type)
                        .getAssociatedEntityName((SessionFactoryImplementor) sessionFactory);
                Class oldTargetClass = targetClass;
                targetClass = sessionFactory.getClassMetadata(otherSideEntityName)
                        .getMappedClass(EntityMode.POJO);
                if (targetClass.equals(oldTargetClass) && !hasMoreThanOneArg) {
                    joinType = CriteriaSpecification.LEFT_JOIN; // default to left join if joining on the same table
                }
                associationStack.add(name);
                final String associationPath = getAssociationPath();
                createAliasIfNeccessary(name, associationPath, joinType);
                // the criteria within an association node are grouped with an implicit AND
                logicalExpressionStack.add(new LogicalExpression(AND));
                invokeClosureNode(callable);
                aliasStack.remove(aliasStack.size() - 1);
                if (!aliasInstanceStack.isEmpty()) {
                    aliasInstanceStack.remove(aliasInstanceStack.size() - 1);
                }
                LogicalExpression logicalExpression = logicalExpressionStack
                        .remove(logicalExpressionStack.size() - 1);
                if (!logicalExpression.args.isEmpty()) {
                    addToCriteria(logicalExpression.toCriterion());
                }
                associationStack.remove(associationStack.size() - 1);
                targetClass = oldTargetClass;

                return name;
            }
        }
    } else if (args.length == 1 && args[0] != null) {
        if (criteria == null) {
            throwRuntimeException(new IllegalArgumentException("call to [" + name + "] not supported here"));
        }

        Object value = args[0];
        Criterion c = null;
        if (name.equals(ID_EQUALS)) {
            return eq("id", value);
        }

        if (name.equals(IS_NULL) || name.equals(IS_NOT_NULL) || name.equals(IS_EMPTY)
                || name.equals(IS_NOT_EMPTY)) {
            if (!(value instanceof String)) {
                throwRuntimeException(new IllegalArgumentException(
                        "call to [" + name + "] with value [" + value + "] requires a String value."));
            }
            String propertyName = calculatePropertyName((String) value);
            if (name.equals(IS_NULL)) {
                c = Restrictions.isNull(propertyName);
            } else if (name.equals(IS_NOT_NULL)) {
                c = Restrictions.isNotNull(propertyName);
            } else if (name.equals(IS_EMPTY)) {
                c = Restrictions.isEmpty(propertyName);
            } else if (name.equals(IS_NOT_EMPTY)) {
                c = Restrictions.isNotEmpty(propertyName);
            }
        }

        if (c != null) {
            return addToCriteria(c);
        }
    }

    throw new MissingMethodException(name, getClass(), args);
}

From source file:id.co.sambaltomat.core.dao.hibernate.GenericDaoHibernate.java

protected void processJoinPath(Criteria criteria, List<JoinPath> joinPaths, ProjectionList projectionList) {
    boolean isDistinctRoot = true;
    if (joinPaths != null && !joinPaths.isEmpty()) {
        for (JoinPath joinPath : joinPaths) {
            if (joinPath.joinType == JoinType.INNER_JOIN)
                criteria.createCriteria(joinPath.path, joinPath.alias, CriteriaSpecification.INNER_JOIN);
            else if (joinPath.joinType == JoinType.LEFT_JOIN)
                criteria.createCriteria(joinPath.path, joinPath.alias, CriteriaSpecification.LEFT_JOIN);
            else if (joinPath.joinType == JoinType.NON_DISTINCT_ROOT_ENTITY)
                isDistinctRoot = false;//from www.j a v  a  2 s  .  com
            else if (joinPath.joinType == JoinType.GROUPING_FIELD) {
                if (projectionList == null) {
                    projectionList = Projections.projectionList();
                }
                projectionList.add(Projections.groupProperty(joinPath.alias));
            } else
                criteria.setFetchMode(joinPath.path, FetchMode.SELECT);

        }
    }
    if (isDistinctRoot)
        criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
}