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

public Criteria createCriteria(String associationPath) throws HibernateException;

Source Link

Document

Create a new Criteria, "rooted" at the associated entity.

Usage

From source file:com.scopix.periscope.templatemanagement.dao.TemplateManagementHibernateDAOImpl.java

License:Open Source License

@Override
public List<MetricTemplate> getMetricTemplateForASituationTemplate(Integer situationTemplateId)
        throws ScopixException {
    log.debug("start");
    List<MetricTemplate> metricTemplates = null;
    try {/* w w w  . j a  v  a2  s.com*/
        Criteria criteria = this.getSession().createCriteria(MetricTemplate.class);
        criteria.addOrder(Order.asc("id"));
        criteria.createCriteria("situationTemplates").add(Restrictions.eq("id", situationTemplateId));
        metricTemplates = criteria.list();
    } catch (Exception e) {
        log.error("Error " + e.getMessage(), e);
        //"periscopeexception.list.error",new String[]{
        throw new ScopixException("label.metricTemplateForASituationTemplate");
    }
    log.debug("end");
    return metricTemplates;
}

From source file:com.smartitengineering.dao.impl.hibernate.AbstractDAO.java

License:Open Source License

@SuppressWarnings("unchecked")
private void processNestedParameter(Criteria criteria, String element, QueryParameter parameter) {
    FetchMode mode;/*from w w w .j a v a 2s  .c  o  m*/
    CompositionQueryParameter queryParameter = QueryParameterCastHelper.COMPOSITION_PARAM_FOR_NESTED_TYPE
            .cast(parameter);
    switch (queryParameter.getFetchMode()) {
    case EAGER:
        mode = FetchMode.EAGER;
        break;
    case SELECT:
        mode = FetchMode.SELECT;
        break;
    case JOIN:
        mode = FetchMode.JOIN;
        break;
    case LAZY:
        mode = FetchMode.LAZY;
        break;
    default:
    case DEFAULT:
        mode = FetchMode.DEFAULT;
        break;
    }
    criteria.setFetchMode(element, ((mode == null) ? FetchMode.JOIN : mode));
    Collection<QueryParameter> nestedParameters = queryParameter.getNestedParameters();
    if (nestedParameters == null || nestedParameters.size() <= 0) {
        return;
    }
    Criteria nestedCriteria = criteria.createCriteria(element);
    for (QueryParameter nestedQueryParameter : nestedParameters) {
        if (!nestedQueryParameter.isInitialized()) {
            continue;
        }
        processCriteria(nestedCriteria, getPropertyName(nestedQueryParameter), nestedQueryParameter);
    }
}

From source file:com.thesett.catalogue.impl.standalone.CatalogueManagerServiceImpl.java

License:Apache License

/** {@inheritDoc} */
public PagingResult executePagedQuery(int from, int number, String databaseEntityName, String entityTypeName,
        String viewTypeName, Criterion criterion, Map<String, Criterion> joins) {
    log.debug("public PagingResult executePagedQuery(int from = " + from + ", int number = " + number
            + ", String databaseEntityName = " + databaseEntityName + ", String entityTypeName = "
            + entityTypeName + ", String viewTypeName = " + viewTypeName + ", Criterion criterion, "
            + "Map<String, Criterion> joins): called");

    Session session = HibernateUtil.getCurrentSession();
    HibernateUtil.beginTransaction();/*w ww  .ja  v  a 2s .  c o m*/

    // Project the id and external id properties and just the remaining properties that are required to project
    // the results onto the specified view type.
    ProjectionList properties = Projections.projectionList().add(Projections.id())
            .add(Property.forName("externalId"));

    ViewType viewType = getCatalogue().getViewType(viewTypeName);

    for (String fieldName : viewType.getAllPropertyTypes().keySet()) {
        properties.add(Property.forName(fieldName));
    }

    // Create the selection criteria for the block.
    Criteria selectCriteria = session.createCriteria(databaseEntityName);

    if (criterion != null) {
        selectCriteria.add(criterion);
    }

    if (joins != null) {
        for (Map.Entry<String, Criterion> entry : joins.entrySet()) {
            String joinEntity = entry.getKey();
            Criterion joinCriterion = entry.getValue();

            selectCriteria.createCriteria(joinEntity).add(joinCriterion);
        }
    }

    selectCriteria.setProjection(properties).setFirstResult(from).setMaxResults(number)
            .setResultTransformer(new ViewInstanceTransformer(viewType, entityTypeName));

    // Create the count criteria.
    Criteria countCriteria = session.createCriteria(databaseEntityName);

    if (criterion != null) {
        countCriteria.add(criterion);
    }

    if (joins != null) {
        for (Map.Entry<String, Criterion> entry : joins.entrySet()) {
            String joinEntity = entry.getKey();
            Criterion joinCriterion = entry.getValue();

            countCriteria.createCriteria(joinEntity).add(joinCriterion);
        }
    }

    countCriteria.setProjection(Projections.rowCount());

    // Run a query to find out how many results there will be and update the list size.
    int count = (Integer) countCriteria.uniqueResult();

    // Execute the query to get the block.
    List<ViewInstance> results = selectCriteria.list();

    return new PagingResult(count, results);
}

From source file:com.tysanclan.site.projectewok.entities.dao.hibernate.GroupDAOImpl.java

License:Open Source License

/**
 * @see com.tysanclan.site.projectewok.dataaccess.EwokHibernateDAO#createCriteria(com.tysanclan.site.projectewok.dataaccess.SearchFilter)
 *///from  www .  j ava2 s.c o  m
@Override
protected Criteria createCriteria(SearchFilter<Group> filter) {
    Criteria criteria = getSession().createCriteria(Group.class);

    if (filter instanceof GroupFilter) {
        GroupFilter groupFilter = (GroupFilter) filter;
        if (groupFilter.getIncludedMembers() != null && !groupFilter.getIncludedMembers().isEmpty()) {

            criteria.createCriteria("groupMembers")
                    .add(Restrictions.in("id", groupFilter.getIncludedMembers()));
        }
        if (groupFilter.getName() != null) {
            criteria.add(Restrictions.eq("name", groupFilter.getName()));
        }
    }

    return criteria;
}

From source file:com.tysanclan.site.projectewok.entities.dao.hibernate.UserDAOImpl.java

License:Open Source License

/**
 * @see com.tysanclan.site.projectewok.dataaccess.EwokHibernateDAO#createCriteria(com.tysanclan.site.projectewok.dataaccess.SearchFilter)
 *///  www.j  a v a2s.  co m
@Override
protected Criteria createCriteria(SearchFilter<User> filter) {
    Criteria criteria = getSession().createCriteria(User.class);

    if (filter instanceof UserFilter) {
        UserFilter userFilter = (UserFilter) filter;
        if (userFilter.getGroup() != null) {
            criteria.createCriteria("groups").add(Restrictions.eq("group_id", userFilter.getGroup().getId()));
        }
        if (userFilter.getUsername() != null) {
            Criterion eq = Restrictions.eq("username", userFilter.getUsername());
            if (eq instanceof SimpleExpression) {
                eq = ((SimpleExpression) eq).ignoreCase();
            }

            criteria.add(eq);
        }
        if (userFilter.getRanks() != null) {
            criteria.add(Restrictions.in("rank", userFilter.getRanks()));
        }
        if (userFilter.getPassword() != null) {
            criteria.add(Restrictions.eq("password", userFilter.getPassword()));
        }
        if (userFilter.getActiveSince() != null) {
            criteria.add(Restrictions.ge("lastAction", userFilter.getActiveSince()));
        }
        if (userFilter.getActiveBefore() != null) {
            criteria.add(Restrictions.lt("lastAction", userFilter.getActiveBefore()));
        }
        if (userFilter.getEmail() != null) {
            criteria.add(Restrictions.eq("eMail", userFilter.getEmail()));
        }
        if (userFilter.getRetired() != null) {
            criteria.add(Restrictions.eq("retired", userFilter.getRetired()));
        }
        if (userFilter.getVacation() != null) {
            criteria.add(Restrictions.eq("vacation", userFilter.getVacation()));
        }
        if (userFilter.getRealm() != null) {
            Criteria sc = criteria.createCriteria("playedGames");
            sc.add(Restrictions.eq("realm", userFilter.getRealm()));
        }

        if (userFilter.getBugReportMaster() != null) {
            criteria.add(Restrictions.eq("bugReportMaster", userFilter.getBugReportMaster()));
        }

        if (userFilter.getTruthsayerNominated() != null) {
            List<TruthsayerNomination> nominated = truthsayerNominationDAO.findAll();
            Set<Long> userids = new HashSet<Long>();
            for (TruthsayerNomination nomination : nominated) {
                userids.add(nomination.getUser().getId());
            }

            if (userFilter.getTruthsayerNominated()) {
                criteria.add(userids.isEmpty() ? Restrictions.sqlRestriction(" 1 = 2")
                        : Restrictions.in("id", userids));
            } else {
                if (!userids.isEmpty()) {
                    criteria.add(Restrictions.not(Restrictions.in("id", userids)));
                }
            }
        }
    }

    return criteria;
}

From source file:com.tysanclan.site.projectewok.entities.dao.hibernate.UserGameRealmDAOImpl.java

License:Open Source License

/**
 * @see com.tysanclan.site.projectewok.entities.dao.UserGameRealmDAO#getActiveUsers(com.tysanclan.site.projectewok.entities.Game,
 *      com.tysanclan.site.projectewok.entities.Realm)
 *//*from  ww  w.j av a2  s .c  o  m*/
@SuppressWarnings("unchecked")
@Override
public List<User> getActiveUsers(Game game, Realm realm) {
    Criteria criteria = getSession().createCriteria(User.class);

    criteria.add(Restrictions.in("rank", MemberUtil.getMemberRanks()));

    Criteria sub = criteria.createCriteria("playedGames");
    sub.add(Restrictions.eq("game", game));
    sub.add(Restrictions.eq("realm", realm));

    return criteria.list();
}

From source file:com.valco.dao.FacturasDAO.java

public List<Facturas> getFacturas(Integer noFactura, Integer noNota) throws Exception {
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction tx = null;/* w w  w  .  j a v  a  2  s .  com*/
    List<Facturas> facturas = new ArrayList<Facturas>();
    try {
        tx = session.beginTransaction();
        Criteria q = session.createCriteria(Facturas.class);
        if (noFactura != null) {
            q.add(Restrictions.eq("codigo", noFactura));
        }
        if (noNota != null) {
            q.createCriteria("notasDeVenta").add(Restrictions.eq("folio", noNota));
            //q.createAlias("notasDeVenta", "nota").add(Restrictions.eqProperty("codigo", noNota.toString()));
        }
        facturas = (List<Facturas>) q.list();

        return facturas;

    } catch (HibernateException he) {
        throw new Exception("Ocurri un error al consultar las facturas.");

    } finally {
        try {
            session.close();
        } catch (HibernateException he) {
            throw new Exception("Ocurri un error al consultar las facturas.");
        }
    }
}

From source file:com.wavemaker.runtime.data.task.AbstractReadTask.java

License:Open Source License

protected Criteria getCriteriaForPath(String path, Map<String, Criteria> criterias, boolean fetch) {

    Criteria rtn = criterias.get(path);//from ww w  . j av a 2s . com
    if (rtn != null) {
        return rtn;
    }

    // find parent, and create a new one
    Tuple.Two<String, String> p = splitPath(path);
    Criteria parent = getCriteriaForPath(p.v1, criterias);

    rtn = parent.createCriteria(p.v2);

    if (fetch) {
        fetch(parent, p.v2);
    }

    criterias.put(path, rtn);

    return rtn;
}

From source file:com.wavemaker.runtime.data.task.SearchTask.java

License:Open Source License

protected Criteria getCritieria(Session session, Object rootSearchObject, final QueryOptions options,
        String dbName) {//from ww  w  .j a va 2 s.  com

    final DataServiceMetaData metaData = getMetaData(dbName);

    Criteria rootCriteria = null;

    final Map<String, Criteria> criterias = new ImmutableEntryMap<String, Criteria>();

    if (rootSearchObject instanceof Class) {
        rootCriteria = initCriteriasMap(criterias, (Class<?>) rootSearchObject, session);
    } else {

        rootCriteria = initCriteriasMap(criterias, rootSearchObject.getClass(), session);

        addExample(rootSearchObject, rootCriteria, options);

        handleIdInSearch(rootSearchObject, rootCriteria, options, metaData);

        ObjectGraphTraversal.ObjectVisitor ov = new ObjectGraphTraversal.ObjectVisitor() {

            @Override
            public void cycle(Object o, Context ctx) {
            }

            @Override
            public void visit(Object queryInstance, Context ctx) {

                String propertyName = ctx.getProperties().get(0);

                if (DataServiceLoggers.taskLogger.isDebugEnabled()) {
                    DataServiceLoggers.taskLogger.debug("Adding criteria on property " + propertyName);
                }

                Criteria parentCriteria = (Criteria) ctx.getValues().get(1);

                if (DataServiceLoggers.taskLogger.isDebugEnabled()) {
                    DataServiceLoggers.taskLogger.debug("Parent criteria is " + parentCriteria);
                }

                Criteria c = parentCriteria.createCriteria(propertyName);

                String k = ObjectUtils.toString(ctx.getProperties(), ServiceConstants.PROPERTY_SEP);

                criterias.put(k, c);

                ctx.getValues().set(0, c);

                addExample(queryInstance, c, options);
                handleIdInSearch(queryInstance, c, options, metaData);
            }
        };

        ObjectGraphTraversal tr = DataServiceUtils.getRelatedTraversal(ov, getObjectAccess(), metaData, false);

        tr.traverse(rootSearchObject, rootCriteria);
    }

    if (addOrder()) {
        applyOrderBy(options, criterias);
    }

    for (String s : options.getSqlRestrictions()) {
        rootCriteria.add(Restrictions.sqlRestriction(s));
    }

    return rootCriteria;
}

From source file:com.webbfontaine.valuewebb.action.pricedb.mp.PRDConsult.java

License:Open Source License

private void fillPDs(Pd pd) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date());
    calendar.add(Calendar.MONTH, -3);
    Date dateOfTodayMinus3Months = calendar.getTime();

    Criteria criteria = PersistenceUtil.getSession(entityManager).createCriteria(Pd.class)
            .setMaxResults(Constants.MAX_RECORDS_IN_FINDER_RESULT).addOrder(Order.desc("id"));
    if (pd.getHsCodeF() != null) {
        criteria.add(Restrictions.like("hsCodeF", pd.getHsCodeF(), MatchMode.START));
    }/*from  w  w w  .  j  av  a  2 s.  c  o m*/
    if (pd.getProductDscF() != null) {
        criteria.add(Restrictions.ilike("productDscF", pd.getProductDscF(), MatchMode.ANYWHERE));
    }
    if (!StringUtils.isEmpty(pd.getValMethod())) {
        criteria.add(Restrictions.ilike("valMethod", pd.getValMethod(), MatchMode.ANYWHERE));
    }

    if (ApplicationProperties.getAppCountry().equals(Constants.CI)) {
        // according to ELL-1186, hardcoded restriction added to qlClassLine, qlValLine
        criteria.add(Restrictions.and(
                Restrictions.or(Restrictions.eq("qlValLine", "1"), Restrictions.isNull("qlValLine")),
                Restrictions.or(Restrictions.eq("qlClassLine", "1"), Restrictions.isNull("qlClassLine"))));
    }

    Criteria ttCrit = criteria.createCriteria("ttGen");
    ttCrit.add(Restrictions.ge("date", dateOfTodayMinus3Months));

    pdDB.addAll(criteria.list());
}