Example usage for org.hibernate Criteria createAlias

List of usage examples for org.hibernate Criteria createAlias

Introduction

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

Prototype

public Criteria createAlias(String associationPath, String alias) throws HibernateException;

Source Link

Document

Join an association, assigning an alias to the joined association.

Usage

From source file:br.ufg.reqweb.dao.TurmaDao.java

@Transactional(readOnly = true)
public List<Turma> find(String termo, Curso curso, boolean periodoAtivo) {
    try {//  w w w . j  av  a2  s. co m
        Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(Turma.class);
        if (periodoAtivo) {
            criteria.createAlias("periodo", "p").add(Restrictions.eq("p.ativo", periodoAtivo));
        }
        if (termo != null && !termo.isEmpty()) {
            criteria.createAlias("disciplina", "d")
                    .add(Restrictions.like("d.nome", termo.toUpperCase(), MatchMode.ANYWHERE));
        }
        if (curso != null) {
            criteria.add(Restrictions.and(Restrictions.eq("d.curso", curso)));
        }
        criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
        return criteria.list();
    } catch (HibernateException | NumberFormatException e) {
        System.out.println("query error: " + e.getMessage());
        return new ArrayList<>();
    }
}

From source file:br.ufg.reqweb.dao.TurmaDao.java

@Transactional(readOnly = true)
public List<Turma> find(int firstResult, int maxResult, String sortField, String sortOrder,
        Map<String, Object> filters) {
    if (filters == null) {
        filters = new HashMap();
    }//  w w w  .j a v a  2  s  . co m
    try {
        Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(Turma.class);
        criteria.createAlias("disciplina", "d");
        for (String field : filters.keySet()) {
            if (field.equals("termo")) {
                criteria.add(Restrictions.and(Restrictions
                        .like("d.nome", filters.get(field).toString(), MatchMode.ANYWHERE).ignoreCase()));
            }
            if (field.equals("periodo")) {
                criteria.add(Restrictions.and(Restrictions.eq("periodo", filters.get(field))));
            }
            if (field.equals("curso")) {
                criteria.add(Restrictions.and(Restrictions.eq("d.curso", filters.get(field))));
            }
        }
        if ((sortField != null && !sortField.isEmpty()) && (sortOrder != null && !sortOrder.isEmpty())) {
            System.out.format("sorted by: %s, ordering %s\n", sortField, sortOrder);
            if (sortOrder.toLowerCase().equals("asc")) {
                criteria.addOrder(Property.forName(sortField).asc());
            }
            if (sortOrder.toLowerCase().equals("desc")) {
                criteria.addOrder(Property.forName(sortField).desc());
            }
        }
        criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
        return criteria.list();
    } catch (HibernateException e) {
        System.out.println("query error: " + e.getMessage());
        return new ArrayList<>();
    }
}

From source file:br.ufg.reqweb.dao.TurmaDao.java

@Transactional(readOnly = true)
public int count(Map<String, Object> filters) {
    if (filters == null) {
        filters = new HashMap();
    }/* w  w  w . ja  va 2  s  .  c o m*/
    try {
        Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(Turma.class);
        criteria.createAlias("disciplina", "d");
        for (String field : filters.keySet()) {
            if (field.equals("termo")) {
                criteria.add(Restrictions.and(Restrictions
                        .like("d.nome", filters.get(field).toString(), MatchMode.ANYWHERE).ignoreCase()));
            }
            if (field.equals("periodo")) {
                criteria.add(Restrictions.and(Restrictions.eq("periodo", filters.get(field))));
            }
            if (field.equals("curso")) {
                criteria.add(Restrictions.and(Restrictions.eq("d.curso", filters.get(field))));
            }
        }
        criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
        return ((Long) criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue();
    } catch (HibernateException e) {
        System.out.println("query error: " + e.getMessage());
        return 0;
    }

}

From source file:ca.myewb.controllers.common.EventList.java

License:Open Source License

private void addFilter(String filter, Criteria criteria) {
    if (filter == null) {
        return; // just in case
    }/*  w  w  w .  j  ava 2s  .  c om*/

    log.debug("Filtering events: " + filter);

    TagModel t = TagModel.getTag(filter);
    criteria.createAlias("tags", "t");

    if (t == null) //won't find anything
    {
        criteria.add(Restrictions.like("t.name", "%" + filter + "%"));
    } else //broaden the search
    {
        criteria.add(Restrictions.like("t.name", "%" + t.getName() + "%"));
    }
}

From source file:ca.myewb.controllers.common.Member.java

License:Open Source License

private void searchMode(Context ctx) throws Exception, RedirectionException {
    MemberSearchForm searchForm = null;/*from w ww  .ja va 2 s  .  c o m*/
    List result = null;

    if (currentUser.isAdmin()) {
        result = hibernateSession.createQuery("FROM GroupChapterModel where visible=true").list();
    }

    // run search, store results in temp list
    if (requestParams.get("Advanced") != null) {
        searchForm = new MemberSearchForm(getInterpageVar("membersearchtarget") + "/search", requestParams,
                true, result);
        ctx.put("advanced", new Boolean(true));
    } else {
        searchForm = new MemberSearchForm(getInterpageVar("membersearchtarget") + "/search", requestParams,
                false, result);
    }

    Message m = searchForm.validate();

    if (m != null) // validation failed, redirect to self, next time we'll be entering the next block
    {
        // Display error and prompt user to fix
        throw getValidationException(searchForm, m, (String) getInterpageVar("membersearchtarget"));
    }

    //form validation succeeded!
    String first = searchForm.getParameter("Firstname");
    String last = searchForm.getParameter("Lastname");
    String email = searchForm.getParameter("Email");
    String city = searchForm.getParameter("City", false);
    String province = searchForm.getParameter("Province", false);
    String lang = searchForm.getParameter("Language", false);
    String gender = searchForm.getParameter("Gender", false);
    String birth = searchForm.getParameter("Birth", false);
    String student = searchForm.getParameter("Student", false);
    String username = searchForm.getParameter("Username", false);

    Criteria crit = hibernateSession.createCriteria(UserModel.class);

    if ((username != null) && !username.equals("")) {
        crit.add(Restrictions.like("username", "%" + username.trim() + "%"));
    }

    if ((first != null) && !first.equals("")) {
        crit.add(Restrictions.like("firstname", "%" + first.trim() + "%"));
    }

    if ((last != null) && !last.equals("")) {
        crit.add(Restrictions.like("lastname", "%" + last.trim() + "%"));
    }

    if ((email != null) && !email.equals("")) {
        List ids = HibernateUtil.currentSession()
                .createSQLQuery("SELECT userid FROM useremails e WHERE e.email LIKE '%" + email.trim() + "%'")
                .list();
        if (!ids.isEmpty()) {
            crit.add(Restrictions.in("id", ids));
        } else {
            crit.add(Restrictions.eq("email", "###invalidemail###")); //so that no results are given
        }
    }

    if ((city != null) && !city.equals("")) {
        crit.add(Restrictions.like("address", "%\n%" + city.trim() + "%\n%"));
    }

    if ((province != null) && !province.equals("")) {
        crit.add(Restrictions.like("address", "%\n%" + province.trim() + "%\n%"));
    }

    if ((lang != null) && !lang.equals("")) {
        crit.add(Restrictions.eq("language", lang.trim()));
    }

    if ((gender != null) && !gender.equals("")) {
        crit.add(Restrictions.eq("gender", gender.trim()));
    }

    if ((birth != null) && !birth.equals("")) {
        crit.add(Restrictions.eq("birth", new Integer(birth)));
    }

    if ((student != null) && !student.equals("")) {
        crit.add(Restrictions.eq("student", new Boolean(student)));
    }

    // Get "my" own lead groups, since I can only
    // see people in groups I lead
    crit.createAlias("roles", "r");
    crit.add(Restrictions.isNull("r.end"));

    if (!currentUser.isAdmin()) {
        crit.add(Restrictions.in("r.group", currentUser.getGroups('l')));
    } else {
        GroupChapterModel chapter = null;

        if (searchForm.getParameter("Chapter", false) != null) {
            if (!searchForm.getParameter("Chapter", false).equals("")) {
                chapter = (GroupChapterModel) hibernateSession.get(GroupChapterModel.class,
                        new Integer(searchForm.getParameter("Chapter", false)));
            }
        }

        if (chapter != null) {
            crit.add(Restrictions.eq("r.group", chapter));
            crit.add(Restrictions.eq("r.level", new Character('m')));
        }

        //don't filter out deleted users!
    }

    crit.add(Restrictions.ne("id", new Integer(1)));

    crit.addOrder(Order.asc("lastname"));
    crit.addOrder(Order.asc("firstname"));
    crit.setProjection(Projections.groupProperty("id"));
    crit.setMaxResults(101);

    List uniqueResultsList = crit.list();
    Vector<UserModel> uniqueResults = new Vector<UserModel>();

    if (uniqueResultsList.size() < 101) {
        Iterator iter = uniqueResultsList.iterator();

        while (iter.hasNext()) {
            Integer i = (Integer) iter.next();

            // This try/catch block is a workaround to the deleted-admin-causes-cgilib-blowup bug
            try {
                uniqueResults.add((UserModel) hibernateSession.get(UserModel.class, i));
            } catch (Exception e) {
                log.warn("Unable to add user to usersearch: id " + i.toString());
            }
        }
    } else {
        ctx.put("tooMany", "yes");
    }

    setInterpageVar("membersearchtempresults", uniqueResultsList);
    ctx.put("tempresults", uniqueResults); //NOT the ids, but the users
    ctx.put("searchmode", "yes");
    if (searchForm == null) {
        log.info("search form was null!");
        throw new RedirectionException(getInterpageVar("membersearchtarget") + "/new");
    }

    ctx.put("form", searchForm);
    ctx.put("target", getInterpageVar("membersearchtarget"));
}

From source file:ca.myewb.controllers.common.PostList.java

License:Open Source License

private void addFilter(String filter, Criteria criteria) {
    if (filter == null) {
        return; // just in case
    }//from ww  w .j a  v  a 2s .co  m

    log.debug("Filtering posts: " + filter);

    TagModel t = TagModel.getTag(filter);
    criteria.createAlias("tags", "t");

    if (t == null) //won't find anything
    {
        criteria.add(Restrictions.like("t.name", "%" + filter + "%"));
    } else //broaden the search
    {
        criteria.add(Restrictions.like("t.name", "%" + t.getName() + "%"));
    }
}

From source file:ca.myewb.controllers.mailing.ListMember.java

License:Open Source License

private List<GroupModel> getControllableGroups() {
    List<GroupModel> lists;

    if (currentUser.isAdmin()) {
        lists = (new SafeHibList<GroupModel>(hibernateSession
                .createQuery("SELECT g FROM GroupModel g where g.visible=true and g.admin=false"))).list();
    } else {/* w ww .  j  av  a  2s  .c  o  m*/
        Criteria crit = hibernateSession.createCriteria(GroupModel.class);

        crit.createAlias("roles", "r");
        crit.add(Restrictions.eq("r.user", currentUser));
        crit.add(Restrictions.isNull("r.end"));
        crit.add(Restrictions.eq("r.level", new Character('l')));
        crit.add(Restrictions.eq("visible", new Boolean(true)));
        crit.add(Restrictions.eq("admin", new Boolean(false)));

        crit.setProjection(Projections.groupProperty("id"));
        lists = (new SafeHibList<GroupModel>(crit)).list();

        Iterator it = lists.iterator();
        List<GroupModel> lists2 = new ArrayList<GroupModel>();

        while (it.hasNext()) {
            lists2.add((GroupModel) hibernateSession.get(GroupModel.class, (Integer) it.next()));
        }

        lists = lists2;
        lists.addAll(currentUser.getChapter().getVisibleChildren());
    }

    return lists;
}

From source file:ch.astina.hesperid.dao.hibernate.FilterGridDataSource.java

License:Apache License

@Override
protected void applyAdditionalConstraints(Criteria criteria) {
    for (String join : joins) {
        criteria.setFetchMode(join, FetchMode.JOIN);
    }//from  w  w w  . j a  v  a2  s. c  om

    for (Entry<String, String> alias : aliases.entrySet()) {
        criteria.createAlias(alias.getKey(), alias.getValue());
    }

    for (Criterion filter : filters) {
        criteria.add(filter);
    }

    if (order != null) {
        criteria.addOrder(order);
    }
}

From source file:ch.systemsx.cisd.openbis.generic.server.dataaccess.db.SampleDAO.java

License:Apache License

private void addSampleCodeCriterion(Criteria criteria, String sampleCode) {
    String[] sampleCodeTokens = sampleCode.split(SampleIdentifier.CONTAINED_SAMPLE_CODE_SEPARARTOR_STRING);
    if (sampleCodeTokens.length > 1) {
        final String containerCode = sampleCodeTokens[0];
        final String code = sampleCodeTokens[1];
        criteria.add(Restrictions.eq("code", CodeConverter.tryToDatabase(code)));
        criteria.createAlias("container", "c");
        criteria.add(Restrictions.eq("c.code", CodeConverter.tryToDatabase(containerCode)));
    } else {/*ww w .  j a va  2s  . co  m*/
        criteria.add(Restrictions.eq("code", CodeConverter.tryToDatabase(sampleCode)));
        criteria.add(Restrictions.isNull("container"));
    }

}

From source file:co.com.codesoftware.logic.ProductoLogic.java

/**
 * Funcion que consulta los prodiuctos por los tres filtros
 *
 * @param categoria//w  ww  . ja  va2  s  .com
 * @param subcategoria
 * @param marca
 * @return
 */
public List<ProductoEntity> consultaProductosCatSubMarc(Integer categoria, String subcategoria, String marca) {
    List<ProductoEntity> respuesta = null;
    try {
        CategoriaEntity categoriaEntity = new CategoriaEntity();
        categoriaEntity.setId(categoria);
        this.initOperation();
        Criteria crit = sesion.createCriteria(ProductoEntity.class);
        if (subcategoria != null && !"".equalsIgnoreCase(subcategoria)) {
            crit.createAlias("referencia", "r")
                    .add(Restrictions.like("r.descripcion", subcategoria, MatchMode.ANYWHERE));
        }
        if (marca != null && "".equalsIgnoreCase(marca)) {
            crit.createAlias("marca", "m").add(Restrictions.like("nombre", marca, MatchMode.ANYWHERE));
        }
        crit.add(Restrictions.eq("estado", "A"));
        crit.add(Restrictions.eq("categoria", categoriaEntity));
        respuesta = crit.list();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return respuesta;
}