Example usage for org.hibernate Criteria createCriteria

List of usage examples for org.hibernate Criteria createCriteria

Introduction

In this page you can find the example usage for org.hibernate Criteria createCriteria.

Prototype

@Deprecated
public Criteria createCriteria(String associationPath, String alias, int joinType) throws HibernateException;

Source Link

Document

Create a new Criteria, "rooted" at the associated entity, assigning the given alias and using the specified join type.

Usage

From source file:ca.qc.cegepoutaouais.tge.pige.server.ManagementServiceImpl.java

License:Open Source License

@Override
public PagingLoadResult<Loan> getLoans(PagingLoadConfig configs) throws PigeException {

    PermissionHelper.checkLoanManagementPermission(getThreadLocalRequest());

    logger.debug("Rcupration des emprunts " + "[Pagination: dpart=" + configs.getOffset() + ", max="
            + configs.getLimit() + "] ...");

    Transaction tx = null;/*from w  ww . j  a  va2  s.c  o  m*/
    List<Loan> loans = null;
    Session session = null;
    Integer loanCount = 0;
    Integer offset = 0;
    Integer limit = 0;

    try {
        session = PigeHibernateUtil.openSession();
        tx = session.beginTransaction();

        Date startDate = null;
        Date endDate = null;

        Criteria loansCriteria = session.createCriteria(Loan.class);
        Criteria usersCriteria = null;

        List<FilterConfig> searchConfigs = configs.get(PIGE.SEARCH_CONFIGS);
        List<FilterConfig> filterConfigs = configs.get(PIGE.FILTER_CONFIGS);

        List<FilterConfig> userParam = null;
        List<FilterConfig> loanParam = null;

        if (searchConfigs != null) {
            for (FilterConfig fc : searchConfigs) {
                if (fc.getField().equals("params")) {
                    logger.debug("Extraction du FilterConfig 'params'...");
                    BaseListFilterConfig blfc = (BaseListFilterConfig) fc;
                    userParam = blfc.get(PIGE.USER_CONFIGS);
                    logger.debug("Extraction de la liste 'user-param'..." + (userParam == null ? "N/D" : "OK"));
                    loanParam = blfc.get(PIGE.LOAN_CONFIGS);
                    logger.debug("Extraction de la liste 'loan-param'..." + (loanParam == null ? "N/D" : "OK"));
                    break;
                }
            }
        }

        Criterion filterCriterion = null;
        Iterator<FilterConfig> itr = null;
        FilterConfig fc = null;

        if (loanParam != null) {
            itr = loanParam.iterator();
            while (itr.hasNext()) {
                fc = itr.next();
                if (fc instanceof BaseDateFilterConfig) {
                    BaseDateFilterConfig dateFC = (BaseDateFilterConfig) fc;
                    startDate = dateFC.get(PIGE.START_DATE, null);
                    endDate = dateFC.get(PIGE.END_DATE, null);
                    itr.remove();
                    break;
                }
            }

            FilterConfig matchModeConfig = new BaseBooleanFilterConfig();
            matchModeConfig.setField(PIGE.MATCH_MODE);
            matchModeConfig.setValue(Boolean.FALSE);
            loanParam.add(matchModeConfig);
            filterCriterion = PigeHibernateUtil.buildFilterCriterion(loanParam);
            if (filterCriterion != null) {
                loansCriteria.add(filterCriterion);
            }

            if (startDate != null) {
                logger.debug("Restrictions sur la date d'chance: entre " + startDate.toString() + " et "
                        + (endDate == null ? new Date() : endDate) + " inclusivement...");
                loansCriteria.add(Restrictions.between(Loan.START_DATE_REF, startDate,
                        (endDate == null ? new Date() : endDate)));
            } else if (endDate != null) {
                logger.debug("Restrictions sur la date d'chance: <= " + endDate.toString());
                loansCriteria.add(Restrictions.le(Loan.START_DATE_REF, endDate));
            }
        }

        if (filterConfigs != null && filterConfigs.size() > 0) {
            filterCriterion = PigeHibernateUtil.buildFilterCriterion(filterConfigs);
            if (filterCriterion != null) {
                loansCriteria.add(filterCriterion);
            }
        }

        usersCriteria = loansCriteria.createCriteria(Loan.USER_REF, "usr", Criteria.LEFT_JOIN);

        if (userParam != null) {
            String userScope = null;
            itr = userParam.iterator();
            while (itr.hasNext()) {
                fc = itr.next();
                if (fc.getField().equals("scope")) {
                    userScope = (String) fc.getValue();
                    itr.remove();
                    break;
                }
            }
            if (userScope != null && !userScope.isEmpty() && !userScope.equals("*")) {
                logger.debug(
                        "Restriction de la recherche sur un usager " + "spcifique: [" + userScope + "] ...");
                usersCriteria.add(Restrictions.like(User.IDENTIFIER_REF, userScope, MatchMode.EXACT));
            } else {
                logger.debug("Restriction de la recherche sur un ou des " + "usager spcifique...");
                filterCriterion = PigeHibernateUtil.buildFilterCriterion(userParam);
                if (filterCriterion != null) {
                    usersCriteria.add(filterCriterion);
                }
            }
        }

        loanCount = (Integer) loansCriteria.setProjection(Projections.rowCount()).uniqueResult();

        offset = configs.getOffset();
        limit = loanCount;
        if (limit > 0 && configs.getLimit() > 0) {
            limit = Math.min(configs.getLimit(), limit);
        }

        logger.debug("Paramtres d'extraction des donnes: dpart=" + offset + ", max=" + limit + "] ...");

        loansCriteria.setProjection(null);
        loansCriteria.setResultTransformer(Criteria.ROOT_ENTITY);

        loans = (List) loansCriteria.addOrder(Order.asc("usr." + User.LOAN_NO_REF)).setFirstResult(offset)
                .setMaxResults(limit).list();

        tx.commit();
        logger.debug("Rcupration russie!");
    } catch (Exception hex) {
        logger.error(hex);
        if (tx != null) {
            tx.rollback();
        }
    } finally {
        if (session != null) {
            session.close();
        }
    }

    if (loans == null) {
        loans = new ArrayList();
    }

    return new BasePagingLoadResult(loans, offset, loanCount);
}

From source file:ca.qc.cegepoutaouais.tge.pige.server.report.ReportDataProvider.java

License:Open Source License

/**
 * Retourne une liste des usagers ayant des emprunts en retards.
 *
 * @return liste des usagers/*from   w  w w . java  2 s.c o  m*/
 */
public List<User> getAllUserWithLateLoan() {

    Transaction tx = null;
    List<User> users = null;
    Session session = null;

    try {
        session = PigeHibernateUtil.openSession();
        tx = session.beginTransaction();

        Criteria userCriteria = session.createCriteria(User.class);
        Criteria loanCriteria = userCriteria.createCriteria(User.LOAN_COLLECTION_REF, "ln", Criteria.LEFT_JOIN);
        loanCriteria.add(Restrictions.eq(Loan.STATUS_REF, LoanStatus.STATUS_LATE));
        users = (List) loanCriteria.list();

        tx.commit();

    } catch (Exception hex) {
        logger.error(hex);
        if (tx != null) {
            tx.rollback();
        }
    } finally {
        if (session != null) {
            session.close();
        }
    }

    if (users == null) {
        users = new ArrayList();
    }

    // Le hashset permet de retirer les doublons provenant de la requte
    // SQL.
    return new ArrayList(new HashSet(users));

}

From source file:com.evolveum.midpoint.repo.sql.query.restriction.ItemRestriction.java

License:Apache License

protected void addNewCriteriaToContext(ItemPath path, Definition def, String realName) {
    ItemPath lastPropPath = path.allExceptLast();
    if (ItemPath.EMPTY_PATH.equals(lastPropPath)) {
        lastPropPath = null;//www.ja v a  2  s  .  co  m
    }

    // Virtual path is defined for example for virtual collections. {c:role/c:assignment} and {c:role/c:iducement}
    // must use the same criteria, therefore {c:role/assigmnents} is also path under which is this criteria saved.
    final ItemPath virtualPath = lastPropPath != null ? new ItemPath(lastPropPath, new QName("", realName))
            : new ItemPath(new QName("", realName));

    Criteria existing = getContext().getCriteria(path);
    if (existing != null) {
        return;
    }

    // If there is already criteria on virtual path, only add new path to aliases and criterias.
    Criteria virtualCriteria = getContext().getCriteria(virtualPath);
    if (virtualCriteria != null) {
        getContext().addAlias(path, virtualCriteria.getAlias());
        getContext().addCriteria(path, virtualCriteria);
        return;
    }

    // get parent criteria
    Criteria pCriteria = getContext().getCriteria(lastPropPath);

    // create new criteria and alias for this relationship
    String alias = getContext().addAlias(path, def);
    Criteria criteria = pCriteria.createCriteria(realName, alias, JoinType.LEFT_OUTER_JOIN);
    getContext().addCriteria(path, criteria);
    //also add virtual path to criteria map
    getContext().addCriteria(virtualPath, criteria);
}

From source file:com.evolveum.midpoint.repo.sql.QueryInterpreterTest.java

License:Apache License

@Test
public void queryOrganizationNorm() throws Exception {
    Session session = open();/*from   w w  w .  j a  va  2s .  c  o  m*/

    try {
        ObjectFilter filter = EqualFilter.createEqual(UserType.F_ORGANIZATION, UserType.class, prismContext,
                PolyStringNormMatchingRule.NAME, new PolyString("asdf", "asdf"));
        ObjectQuery query = ObjectQuery.createObjectQuery(filter);

        Criteria main = session.createCriteria(RUser.class, "u");
        ProjectionList projections = Projections.projectionList();
        addFullObjectProjectionList("u", projections, false);
        main.setProjection(projections);

        Criteria o = main.createCriteria("organization", "o", JoinType.LEFT_OUTER_JOIN);

        o.add(Restrictions.eq("o.norm", "asdf"));

        String expected = HibernateToSqlTranslator.toSql(main);
        String real = getInterpretedQuery(session, UserType.class, query);

        LOGGER.info("exp. query>\n{}\nreal query>\n{}", new Object[] { expected, real });
        AssertJUnit.assertEquals(expected, real);
    } finally {
        close(session);
    }
}

From source file:com.evolveum.midpoint.repo.sql.QueryInterpreterTest.java

License:Apache License

@Test
public void queryOrganizationOrig() throws Exception {
    Session session = open();/*w  w  w.j  a va 2s. co  m*/
    try {
        ObjectFilter filter = EqualFilter.createEqual(UserType.F_ORGANIZATION, UserType.class, prismContext,
                PolyStringOrigMatchingRule.NAME, new PolyString("asdf", "asdf"));
        ObjectQuery query = ObjectQuery.createObjectQuery(filter);

        Criteria main = session.createCriteria(RUser.class, "u");
        ProjectionList projections = Projections.projectionList();
        addFullObjectProjectionList("u", projections, false);
        main.setProjection(projections);

        Criteria o = main.createCriteria("organization", "o", JoinType.LEFT_OUTER_JOIN);

        o.add(Restrictions.eq("o.orig", "asdf"));

        String expected = HibernateToSqlTranslator.toSql(main);
        String real = getInterpretedQuery(session, UserType.class, query);

        LOGGER.info("exp. query>\n{}\nreal query>\n{}", new Object[] { expected, real });
        AssertJUnit.assertEquals(expected, real);
    } finally {
        close(session);
    }
}

From source file:com.evolveum.midpoint.repo.sql.QueryInterpreterTest.java

License:Apache License

@Test
public void queryOrganizationStrict() throws Exception {
    Session session = open();/*from w w  w.  j av a  2 s. c o m*/
    try {
        ObjectFilter filter = EqualFilter.createEqual(UserType.F_ORGANIZATION, UserType.class, prismContext,
                null, new PolyString("asdf", "asdf"));
        ObjectQuery query = ObjectQuery.createObjectQuery(filter);

        Criteria main = session.createCriteria(RUser.class, "u");
        ProjectionList projections = Projections.projectionList();
        addFullObjectProjectionList("u", projections, false);
        main.setProjection(projections);

        Criteria o = main.createCriteria("organization", "o", JoinType.LEFT_OUTER_JOIN);

        o.add(Restrictions.conjunction().add(Restrictions.eq("o.orig", "asdf"))
                .add(Restrictions.eq("o.norm", "asdf")));

        String expected = HibernateToSqlTranslator.toSql(main);
        String real = getInterpretedQuery(session, UserType.class, query);

        LOGGER.info("exp. query>\n{}\nreal query>\n{}", new Object[] { expected, real });
        AssertJUnit.assertEquals(expected, real);
    } finally {
        close(session);
    }
}

From source file:com.evolveum.midpoint.repo.sql.QueryInterpreterTest.java

License:Apache License

@Test
public void queryDependent() throws Exception {
    Session session = open();/*from  ww w  . j  a v a 2  s.  c  om*/

    try {
        Criteria main = session.createCriteria(RTask.class, "t");
        Criteria d = main.createCriteria("dependent", "d", JoinType.LEFT_OUTER_JOIN);
        d.add(Restrictions.eq("d.elements", "123456"));
        ProjectionList projections = Projections.projectionList();
        addFullObjectProjectionList("t", projections, false);
        main.setProjection(projections);

        String expected = HibernateToSqlTranslator.toSql(main);

        ObjectFilter filter = EqualFilter.createEqual(TaskType.F_DEPENDENT, TaskType.class, prismContext, null,
                "123456");
        ObjectQuery query = ObjectQuery.createObjectQuery(filter);
        String real = getInterpretedQuery(session, TaskType.class, query);

        LOGGER.info("exp. query>\n{}\nreal query>\n{}", new Object[] { expected, real });
        AssertJUnit.assertEquals(expected, real);
    } finally {
        close(session);
    }
}

From source file:com.evolveum.midpoint.repo.sql.QueryInterpreterTest.java

License:Apache License

@Test
public void queryGenericLong() throws Exception {
    Session session = open();//  ww w .j a v  a 2  s  .  c om
    try {
        Criteria main = session.createCriteria(RGenericObject.class, "g");

        Criteria stringExt = main.createCriteria("longs", "l", JoinType.LEFT_OUTER_JOIN);

        //and
        Criterion c1 = Restrictions.eq("name.norm", "generic object");
        //and
        Conjunction c2 = Restrictions.conjunction();
        c2.add(Restrictions.eq("l.ownerType", RObjectExtensionType.EXTENSION));
        c2.add(Restrictions.eq("l.name", new QName("http://example.com/p", "intType")));
        c2.add(Restrictions.eq("l.value", 123L));

        Conjunction conjunction = Restrictions.conjunction();
        conjunction.add(c1);
        conjunction.add(c2);
        main.add(conjunction);
        ProjectionList projections = Projections.projectionList();
        addFullObjectProjectionList("g", projections, false);
        main.setProjection(projections);

        String expected = HibernateToSqlTranslator.toSql(main);
        String real = getInterpretedQuery(session, GenericObjectType.class,
                new File(TEST_DIR, "query-and-generic.xml"));

        LOGGER.info("exp. query>\n{}\nreal query>\n{}", new Object[] { expected, real });
        AssertJUnit.assertEquals(expected, real);
    } finally {
        close(session);
    }
}

From source file:com.evolveum.midpoint.repo.sql.QueryInterpreterTest.java

License:Apache License

@Test
public void queryOrComposite() throws Exception {
    Session session = open();//from  w  ww.j  a  v a 2s .  c o m
    try {
        Criteria main = session.createCriteria(RShadow.class, "r");
        ProjectionList projections = Projections.projectionList();
        addFullObjectProjectionList("r", projections, false);
        main.setProjection(projections);

        Criteria stringExt = main.createCriteria("strings", "s1", JoinType.LEFT_OUTER_JOIN);

        //or
        Criterion c1 = Restrictions.eq("intent", "some account type");
        //or
        Conjunction c2 = Restrictions.conjunction();
        c2.add(Restrictions.eq("s1.ownerType", RObjectExtensionType.ATTRIBUTES));
        c2.add(Restrictions.eq("s1.name", new QName("http://midpoint.evolveum.com/blabla", "foo")));
        c2.add(Restrictions.eq("s1.value", "foo value"));
        //or
        Conjunction c3 = Restrictions.conjunction();
        c3.add(Restrictions.eq("s1.ownerType", RObjectExtensionType.EXTENSION));
        c3.add(Restrictions.eq("s1.name", new QName("http://example.com/p", "stringType")));
        c3.add(Restrictions.eq("s1.value", "uid=test,dc=example,dc=com"));
        //or
        Conjunction c4 = Restrictions.conjunction();
        c4.add(Restrictions.eq("r.resourceRef.targetOid", "d0db5be9-cb93-401f-b6c1-86ffffe4cd5e"));
        c4.add(Restrictions.eq("r.resourceRef.type", QNameUtil.qNameToUri(ResourceType.COMPLEX_TYPE)));

        Disjunction disjunction = Restrictions.disjunction();
        disjunction.add(c1);
        disjunction.add(c2);
        disjunction.add(c3);
        disjunction.add(c4);
        main.add(disjunction);

        String expected = HibernateToSqlTranslator.toSql(main);
        String real = getInterpretedQuery(session, ShadowType.class,
                new File(TEST_DIR, "query-or-composite.xml"));

        LOGGER.info("exp. query>\n{}\nreal query>\n{}", new Object[] { expected, real });
        AssertJUnit.assertEquals(expected, real);
    } finally {
        close(session);
    }
}

From source file:com.evolveum.midpoint.repo.sql.QueryInterpreterTest.java

License:Apache License

@Test
public void queryAccountByAttributesAndResourceRef() throws Exception {
    Session session = open();/*from   w  w w  .  j  a v  a 2 s  .  c  om*/
    try {
        Criteria main = session.createCriteria(RShadow.class, "r");

        Criteria stringAttr = main.createCriteria("strings", "s1x", JoinType.LEFT_OUTER_JOIN);

        //and
        Conjunction c1 = Restrictions.conjunction();
        c1.add(Restrictions.eq("r.resourceRef.targetOid", "aae7be60-df56-11df-8608-0002a5d5c51b"));
        c1.add(Restrictions.eq("r.resourceRef.type", QNameUtil.qNameToUri(ResourceType.COMPLEX_TYPE)));
        //and
        Conjunction c2 = Restrictions.conjunction();
        c2.add(Restrictions.eq("s1x.ownerType", RObjectExtensionType.ATTRIBUTES));
        c2.add(Restrictions.eq("s1x.name", new QName("http://midpoint.evolveum.com/blabla", "foo")));
        c2.add(Restrictions.eq("s1x.value", "uid=jbond,ou=People,dc=example,dc=com"));

        Conjunction conjunction = Restrictions.conjunction();
        conjunction.add(c1);
        conjunction.add(c2);
        main.add(conjunction);
        ProjectionList projections = Projections.projectionList();
        addFullObjectProjectionList("r", projections, false);
        main.setProjection(projections);

        String expected = HibernateToSqlTranslator.toSql(main);
        String real = getInterpretedQuery(session, ShadowType.class,
                new File(TEST_DIR, "query-account-by-attributes-and-resource-ref.xml"));

        LOGGER.info("exp. query>\n{}\nreal query>\n{}", new Object[] { expected, real });
        AssertJUnit.assertEquals(expected, real);
    } finally {
        close(session);
    }
}