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:au.org.theark.core.dao.ArkAuthorisationDao.java

License:Open Source License

@SuppressWarnings("unchecked")
public List<Study> getAssignedChildStudyListForUser(ArkUserVO arkUserVo) {
    List<Study> studyList = new ArrayList<Study>(0);

    try {/*from w ww . j a  va2s  . co m*/
        ArkUser arkUser = getArkUser(arkUserVo.getArkUserEntity().getLdapUserName());

        /* Get only the studies the ArkUser is linked to via the ArkUserRole */
        Criteria criteria = getSession().createCriteria(ArkUserRole.class);
        criteria.add(Restrictions.eq("arkUser", arkUser));
        // Restrict to child studies (without parent)
        Criteria studyCriteria = criteria.createCriteria("study");
        studyCriteria.add(Restrictions.eq("parentStudy", arkUserVo.getStudy()));
        studyCriteria.add(Restrictions.neProperty("id", "parentStudy.id"));
        studyCriteria.addOrder(Order.asc("name"));
        ProjectionList projectionList = Projections.projectionList();
        projectionList.add(Projections.groupProperty("study"), "study");
        criteria.setProjection(projectionList);

        studyList = criteria.list();
    } catch (EntityNotFoundException e) {
        log.error(e.getMessage(), e);
    }

    return studyList;
}

From source file:br.com.bean.RestControllers.turmaController.java

@RequestMapping(value = "busca-turmas", method = RequestMethod.GET)
@ResponseBody// ww w . j a v a 2 s.  c o  m
public String buscaTurmas(long faculdadeId) throws ParseException {
    Session sessao = HibernateUtility.getSession();
    Transaction transacao = sessao.beginTransaction();
    try {
        Criteria turmaCrit = sessao.createCriteria(Turma.class);
        turmaCrit.add(Restrictions.eq("ativo", 1));
        Criteria faculdadeCrit = turmaCrit.createCriteria("faculdade");
        faculdadeCrit.add(Restrictions.eq("faculdadeId", faculdadeId));
        turmaCrit.setResultTransformer(DistinctRootEntityResultTransformer.INSTANCE);
        List<Turma> listaDeTurmas = turmaCrit.list();
        for (Turma t : listaDeTurmas) {
            t.setFaculdade(null);
        }
        Type TipolistaDeTurmas = new TypeToken<List<Turma>>() {
        }.getType();
        Gson gson = new GsonBuilder().registerTypeAdapter(Collection.class, new CollectionDeserializer())
                .create();
        return gson.toJson(listaDeTurmas, TipolistaDeTurmas);
    } catch (HibernateException e) {
        transacao.rollback();
        return null;
    } finally {
        sessao.close();
    }
}

From source file:br.com.sgejs.dao.DaoArquivo.java

public List<Arquivo> getArquivosDoAluno(long id) throws HibernateException {
    Criteria criArquivo = sessao.createCriteria(classe, "p");
    criArquivo.setProjection(Projections.projectionList().add(Projections.property("p.id").as("id"))
            .add(Projections.property("p.ano").as("ano")).add(Projections.property("p.curso").as("curso"))
            .add(Projections.property("p.tipo").as("tipo")).add(Projections.property("p.caixa").as("caixa"))
            .add(Projections.property("p.criacao").as("criacao")))
            .setResultTransformer(new AliasToBeanResultTransformer(Arquivo.class));
    criArquivo.createCriteria("alunos").add(Restrictions.eq("id", id));
    return criArquivo.list();
}

From source file:br.gov.jfrj.siga.hibernate.ExDao.java

License:Open Source License

public void indexarUltimas(int desde) throws Exception {

    System.out.println("Indexando documentos...");
    long inicio = new Date().getTime();

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.MINUTE, desde);
    Date dtIni = cal.getTime();/*from w  w w.ja  v a2 s . com*/

    Criteria crit = getSessao().createCriteria(ExDocumento.class);
    crit.createCriteria("exMovimentacaoSet").add(Restrictions.gt("dtIniMov", dtIni));
    crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    /*
     * Query indexQuery = getSessao() .createQuery( "from ExDocumento as doc
     * inner join doc.exMovimentacaoSet as mov where mov.dtIniMov >=
     * :dtIni"); indexQuery.setParameter("dtIni", dtIni);
     */

    FullTextSession fullTextSession = Search.getFullTextSession(getSessao());
    // List<ExDocumento> list = indexQuery.list();
    List<ExDocumento> list = crit.list();
    Transaction tx = fullTextSession.beginTransaction();
    for (ExDocumento doc : list) {
        System.out.println(" . " + doc.getIdDoc());
        fullTextSession.purge(ExDocumento.class, doc);
        if (doc.isIndexavel())
            fullTextSession.index(doc);
    }
    tx.commit();
    fullTextSession.clear();
    getSessao().clear();
    //System.gc();

    // fullTextSession.close();
    System.out.println("Durao da indexao de documentos: " + (new Date().getTime() - inicio));

}

From source file:br.ufg.calendario.dao.EventoDao.java

@Transactional(readOnly = true)
public List<Evento> listar(int first, int pageSize, String sortField, String sortOrder,
        Map<String, Object> filters) {
    Session session = sessionFactory.getCurrentSession();
    Criteria criteria = session.createCriteria(Evento.class);
    criteria.setFirstResult(first);//from   ww w . ja  v a2  s.co  m
    criteria.setMaxResults(pageSize);

    if ((sortField != null && !sortField.isEmpty()) && (sortOrder != null && !sortOrder.isEmpty())) {
        if (sortOrder.equals("ASCENDING")) {
            criteria.addOrder(Order.asc(sortField));
        }
        if (sortOrder.equals("DESCENDING")) {
            criteria.addOrder(Order.desc(sortField));
        }
    } else {
        criteria.addOrder(Order.asc("id"));
    }
    if (filters != null && !filters.isEmpty()) {
        for (String key : filters.keySet()) {
            if (key.equals("termo")) {
                List foundList = buscarTermo(session, filters.get("termo").toString());
                if (foundList.size() > 0) {
                    criteria.add(Restrictions.in("id", foundList));
                } else {
                    criteria.add(Restrictions.or(
                            Restrictions.like("assunto", filters.get(key).toString(), MatchMode.ANYWHERE)
                                    .ignoreCase(),
                            Restrictions.like("descricao", filters.get(key).toString(), MatchMode.ANYWHERE)
                                    .ignoreCase()));
                }
            }

            if (key.equals("interessado")) {
                Interessado interessado = (Interessado) filters.get(key);
                System.out.println("interessado: " + interessado.getNome());
                criteria.createCriteria("interessado").add(Restrictions.eq("id", interessado.getId()));
            }

            if (key.equals("regional")) {
                Regional regional = (Regional) filters.get(key);
                System.out.println("regional: " + regional.getNome());
                criteria.createCriteria("regional").add(Restrictions.eq("id", regional.getId()));
            }

            if (key.equals("periodo")) {
                Map periodo = (Map) filters.get(key);
                criteria.add(Restrictions
                        .or(Restrictions.between("inicio", periodo.get("inicio"), periodo.get("termino")))
                        .add(Restrictions.between("termino", periodo.get("inicio"), periodo.get("termino"))));
            }

            if (key.equals("calendario")) {
                criteria.createAlias("calendario", "c");
                criteria.add(Restrictions.eq("c.ano", ((Calendario) filters.get(key)).getAno()));
            }

        }
    }
    if (filters == null || !filters.containsKey("calendario")) {
        criteria.createAlias("calendario", "c");
        criteria.add(Restrictions.eq("c.ativo", true));
    }
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    List<Evento> resultado = criteria.list();
    for (Evento evt : resultado) {
        Hibernate.initialize(evt.getInteressado());
        Hibernate.initialize(evt.getRegional());
    }
    return resultado;
}

From source file:by.telecom.subscriberapp.DAO.LogDaoImpl.java

@Override
public List<Log> getByParameter(String name, Date dateStart, Date dateEnd, String type, String comment,
        String sort, String orderType) {
    Session session = null;/*from   www  . j a  v  a2s . c om*/
    List<Log> logs = new ArrayList<Log>();
    try {
        session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Criteria criteria = session.createCriteria(Log.class).add(Restrictions.ge("date", dateStart))
                .add(Restrictions.le("date", dateEnd)).add(Restrictions.like("type", "%" + type + "%"))
                .add(Restrictions.like("comment", "%" + comment + "%"));
        Order order = Order.asc(sort);
        if (orderType.equals("desc"))
            order = Order.desc(sort);
        if (sort.equals("name"))
            criteria = criteria.createCriteria("user").add(Restrictions.like("name", "%" + name + "%"))
                    .addOrder(order);
        else
            criteria = criteria.addOrder(order).createCriteria("user")
                    .add(Restrictions.like("name", "%" + name + "%"));

        logs = criteria.list();
        session.getTransaction().commit();
    } catch (Exception e) {
        e.printStackTrace(System.out);
    } finally {
        if (session != null && session.isOpen()) {
            session.close();
        }
    }
    return logs;
}

From source file:by.telecom.subscriberapp.DAO.PhoneDaoImpl.java

@Override
public List<Phone> getAll(String sort, String orderType) {
    Session session = null;/*w ww . j  a  v  a 2  s . c om*/
    List<Phone> all = new ArrayList<Phone>();
    try {
        session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Criteria criteria = session.createCriteria(Phone.class);
        Order order = Order.asc(sort);
        if (sort.equals("name"))
            criteria = criteria.createCriteria("subscriber");
        if (orderType.equals("desc"))
            order = Order.desc(sort);
        all = criteria.addOrder(order).list();
    } catch (Exception e) {
        e.printStackTrace(System.out);
    } finally {
        if (session != null && session.isOpen()) {
            session.close();
        }
    }
    return all;
}

From source file:by.telecom.subscriberapp.DAO.PhoneDaoImpl.java

@Override
public List<Phone> getByParameter(String number, String band, String security, String scv, String adsl,
        String name, String sort, String orderType) {
    Session session = null;//from  w  w  w .ja  v  a 2 s .  c o m
    List<Phone> phones = new ArrayList<Phone>();
    try {
        session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Criteria criteria = session.createCriteria(Phone.class).add(Restrictions.like("number", number + "%"))
                .add(Restrictions.like("band", band + "%")).add(Restrictions.like("security", security + "%"))
                .add(Restrictions.like("scv", scv + "%")).add(Restrictions.like("adsl", adsl + "%"));
        Order order = Order.asc(sort);
        if (orderType.equals("desc"))
            order = Order.desc(sort);
        if (sort.equals("name"))
            criteria = criteria.createCriteria("subscriber").add(Restrictions.like("name", "%" + name + "%"))
                    .addOrder(order);
        else
            criteria = criteria.addOrder(order).createCriteria("subscriber")
                    .add(Restrictions.like("name", "%" + name + "%"));

        phones = criteria.list();
        session.getTransaction().commit();
    } catch (Exception e) {
        e.printStackTrace(System.out);
    } finally {
        if (session != null && session.isOpen()) {
            session.close();
        }
    }
    return phones;
}

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

License:Open Source License

@Override
public List<Category> getCategories(Category parent, Boolean includeUnclassified) throws PigeException {

    logger.debug("Rcupration des catgories...");

    Transaction tx = null;//w  ww .j a v  a 2 s. c  o  m
    List<Category> categories = null;
    Session session = null;

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

        Criteria criteria = session.createCriteria(Category.class);
        if (parent != null) {
            logger.debug("category != null: " + parent.getName());
            criteria.add(Restrictions.eq(Category.PARENT_REF, parent));
        } else {
            criteria.add(Restrictions.isNull(Category.PARENT_REF));
        }
        criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

        categories = (List) criteria.addOrder(Order.asc(Category.NAME_REF)).list();

        if (categories != null) {
            for (Category c : categories) {
                Criteria itemCrit = session.createCriteria(Item.class);
                itemCrit.createCriteria(Item.CATEGORIES_REF)
                        .add(Restrictions.like(Category.PATH_REF, c.getPath(), MatchMode.START));
                itemCrit.setProjection(Projections.distinct(Projections.rowCount()));
                c.setItemCount((Integer) itemCrit.uniqueResult());
            }
        }

        //  la racine seulement.
        if (includeUnclassified && parent == null) {
            Category unclassified = new Category();
            unclassified.setId(Category.UNCLASSIFIED_CATEGORY_ID);
            Criteria itemCrit = session.createCriteria(Item.class);
            itemCrit.add(Restrictions.sizeEq(Item.CATEGORIES_REF, 0));
            itemCrit.setProjection(Projections.distinct(Projections.rowCount()));
            unclassified.setItemCount((Integer) itemCrit.uniqueResult());
            categories.add(unclassified);
        }

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

    return categories;
}

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

License:Apache License

public MaterialPE tryFindMaterial(MaterialIdentifier identifier) {
    assert identifier != null : "identifier not given";

    String code = CodeConverter.tryToDatabase(identifier.getCode());
    String typeCode = CodeConverter.tryToDatabase(identifier.getTypeCode());

    final Criteria criteria = getSession().createCriteria(ENTITY_CLASS);
    criteria.add(Restrictions.eq("code", code));
    criteria.createCriteria("materialType").add(Restrictions.eq("code", typeCode));
    criteria.setFetchMode("materialType.materialTypePropertyTypesInternal", FetchMode.JOIN);
    final MaterialPE material = (MaterialPE) criteria.uniqueResult();
    if (operationLog.isDebugEnabled()) {
        operationLog/*from ww  w  .  j  a v  a  2 s .  c o m*/
                .debug(String.format("Following material '%s' has been found for " + "code '%s' and type '%s'.",
                        material, code, typeCode));
    }
    return material;
}