Package org.hibernate.criterion

Examples of org.hibernate.criterion.DetachedCriteria


  /**
   * @see br.jus.tjrn.arq.persistence.CrudDao#findAll(sortField, sortOrder)
   */
  @Override
  public List<T> findAll(String sortField, Boolean sortOrder){
      DetachedCriteria criteria = DetachedCriteria.forClass(getPersistentClass());
        if(sortField != null) {
            if(sortOrder) {
                criteria.addOrder(Order.asc(sortField));
            } else {
                criteria.addOrder(Order.desc(sortField));
            }
        }
        return ht.findByCriteria(criteria);
  }
View Full Code Here


        }

      List<T> result = new ArrayList<T>();

      try {
          DetachedCriteria criteria = mountCriteriaForFindByAttributes(entity, null, null);
          result.addAll(ht.findByCriteria(criteria, firstResult, maxResult));
        } catch (Exception e) {
            throw new DataAccessException(e);
        }
View Full Code Here

        if (entity == null) {
            throw new IllegalArgumentException("Para o parâmetro entity, forneça um objeto não nulo");
        }

        try {
            DetachedCriteria criteria = mountCriteriaForFindByAttributes(entity, sortField, sortOrder);
            result.addAll(ht.findByCriteria(criteria, firstResult, maxResult));
        } catch (Exception e) {
            throw new DataAccessException(e);
        }
View Full Code Here

            Object[] propertyValues = meta.getPropertyValues(entity, EntityMode.POJO);
           
            Integer id = entity.getId();
            ReflectionUtils.invokeMethod(new PropertyDescriptor(meta.getIdentifierPropertyName(), getPersistentClass()).getWriteMethod(), entity, new Object[] {null});
             
            DetachedCriteria criteria = DetachedCriteria.forClass(getPersistentClass());
             
            if (id != null) {
                criteria.add(Restrictions.not(Restrictions.eq(meta.getIdentifierPropertyName(), id)));
            }
           
            for ( int i=0; i<propertyNames.length; i++ ) {
                String name = propertyNames[i];
                Type type = propertyTypes[i];
                Object value = propertyValues[i];
               
                if (value != null && !type.isCollectionType()) {
                    criteria.add(Restrictions.eq(name, value));
                }
            }
           
            result = countByCriteria(criteria);
           
View Full Code Here

     * @see org.hibernate.type.Type
     * @see org.hibernate.metadata.ClassMetadata
     *
     */
    private DetachedCriteria mountCriteriaForFindByAttributes(T entity, final String sortField, final Boolean sortOrder) {
        DetachedCriteria criteria = DetachedCriteria.forClass(getPersistentClass());

        SessionFactory sessionFactory = ht.getSessionFactory();
        ClassMetadata meta = sessionFactory.getClassMetadata(getPersistentClass());

        String[] propertyNames = meta.getPropertyNames();
        Type[] propertyTypes = meta.getPropertyTypes();
        Object[] propertyValues = meta.getPropertyValues(entity, EntityMode.POJO);

        /*
         * Adicionando o atributo identificador único(id) caso o mesmo tenha
         * sido informado e exista um atributo chave.
         */
        if (entity.getId() != null  &&  meta.getIdentifierPropertyName()!=null) {
            criteria.add(Restrictions.eq(meta.getIdentifierPropertyName(), entity.getId()));
        }

        /*
         * Varrendo todos os atributos da entidade. Como na listagem não consta
         * o atributo identificador único(id), este foi observado na rotina anterior.
         */
        log.debug("Iniciando o processo de composição da consulta para método FindByAttributes.");
        for ( int i=0; i<propertyNames.length; i++ ) {
            String name = propertyNames[i];
            Type type = propertyTypes[i];
            Object value = propertyValues[i];
            log.debug("Nome do atributo:" + name + " - Tipo (Hibernate):" + type.getName() + " - Valor:" + value);

            // Se o atributo tem um valor definido.
            if (value != null) {

                if (!type.isCollectionType()) {

                    log.debug("Atributo adicionado: " + name);

                    FindByAttribute findByAttibute = getFindByAttributeAnnotation(name);
                    if (findByAttibute == null) {
                        if (type instanceof StringType) {
                            criteria.add(Restrictions.like(name, "%" + value + "%"));
                        } else {
                            criteria.add(Restrictions.eq(name, value));
                        }
                    } else {
                        if (type instanceof StringType) {

                            StringComparation stringComparation = findByAttibute.stringComparation();
                            if(stringComparation != null && stringComparation == StringComparation.EXACT) {
                                criteria.add(Restrictions.eq(name, value));
                            } else if(stringComparation != null && stringComparation == StringComparation.END) {
                                criteria.add(Restrictions.like(name, "%" + value));
                            } else if(stringComparation != null && stringComparation == StringComparation.START) {
                                criteria.add(Restrictions.like(name, value + "%"));
                            } else {
                                criteria.add(Restrictions.like(name, "%" + value + "%"));
                            }

                        } else if (type instanceof TimestampType) {
                            DateComparation dateComparation = findByAttibute.dateComparation();
                            if(dateComparation != null && dateComparation == DateComparation.EXACT) {
                                criteria.add(Restrictions.eq(name, value));
                            } else if(dateComparation != null && dateComparation == DateComparation.GREATER_THAN) {
                                criteria.add(Restrictions.ge(name, value));
                            } else if(dateComparation != null && dateComparation == DateComparation.LESS_THAN) {
                                criteria.add(Restrictions.le(name, value));
                            } else if(dateComparation != null && dateComparation == DateComparation.EXACT_DMY) {
                                Date dataInicial = DateUtils.truncate(value, Calendar.DAY_OF_MONTH);
                                Date dataFinal   = DateUtils.addMilliseconds(dataInicial, ONE_DAY_IN_MILLISECONDS);
                                criteria.add(Restrictions.between(name, dataInicial, dataFinal));
                            }

                        } else {
                            criteria.add(Restrictions.eq(name, value));
                        }

                    }

                } else {
                    log.debug("Atributo não adicionado por ser uma coleção: " + name);
                }
            } else {
                log.debug("Atributo não adicionado por estar \"null\": " + name);
            }
        }

        if (sortField != null) {

            String[] fields = sortField.split("\\,");
            for (String field : fields) {

                if (field.split("\\.").length == 1) {
                    log.debug("Adicionando resultado da consulta por ordem do campo "+field.trim()+" SEM criação de alias");
                    if (sortOrder) {
                        log.debug("Ordenação adicionada: " + sortField + " ASC");
                        criteria.addOrder(Order.asc(sortField));
                    } else {
                        log.debug("Ordenação adicionada: " + sortField + " DESC");
                        criteria.addOrder(Order.desc(sortField));
                    }

                } else {
                    String innerClass = field.split("\\.")[0].trim();
                    String innerAttribute = field.split("\\.")[1].trim();
                    log.debug("Adicionando resultado da consulta por ordem do campo "+innerClass+"."+innerAttribute+" COM criação de alias");
                    if (sortOrder) {
                        log.debug("Ordenação adicionada: " + sortField + " ASC");
                        criteria.createAlias(innerClass, innerClass).addOrder(Order.asc(innerClass+"."+innerAttribute));
                    } else {
                        log.debug("Ordenação adicionada: " + sortField + " DESC");
                        criteria.createAlias(innerClass, innerClass).addOrder(Order.desc(innerClass+"."+innerAttribute));
                    }
                }

            }

View Full Code Here

  @Override
    public Integer countByAttributes(T entity) {
      Integer result = 0;

      try {
          DetachedCriteria criteria = mountCriteriaForFindByAttributes(entity, null, null);

          result = countByCriteria(criteria);
        } catch (Exception e) {
            throw new DataAccessException(e);
        }
View Full Code Here

        try {
          ClassMetadata meta = getClassMetadata();
          Integer id = entity.getId();
          ReflectionUtils.invokeMethod(new PropertyDescriptor(meta.getIdentifierPropertyName(), getPersistentClass()).getWriteMethod(), entity, new Object[] {null});
           
          DetachedCriteria criteria = mountCriteriaForFindByAttributes(entity, null, null);
           
          if (id != null) {
              criteria.add(Restrictions.not(Restrictions.eq(meta.getIdentifierPropertyName(), id)));
          }
         
          result = countByCriteria(criteria);
         
        } catch (Exception e) {
View Full Code Here

        if (maxResult < 0) {
            throw new IllegalArgumentException("Para o parâmetro maxResult, forneça um valor maior ou igual a zero");
        }

        try {
            DetachedCriteria criteria = DetachedCriteria.forClass(getPersistentClass());
            for (Criterion c : criterion) {
                criteria.add(c);
            }

            result = ht.findByCriteria(criteria, firstResult, maxResult);
        } catch (Exception e) {
            throw new DataAccessException(e);
View Full Code Here

     * @see br.jus.tjrn.arq.persistence.CrudDao#findAll(int, int, String, Boolean)
     */
  @Override
    public List<T> findAll(int firstResult, int maxResult, String sortField, Boolean sortOrder) {
      List<T> result = null;
      DetachedCriteria d = DetachedCriteria.forClass(getPersistentClass());
        if(sortField != null) {
            if(sortOrder) {
                d.addOrder(Order.asc(sortField));
            } else {
                d.addOrder(Order.desc(sortField));
            }
        }
        result = ht.findByCriteria(d, firstResult, maxResult);
        return result;

View Full Code Here

    return sample;

  }

  public Airport searchAirport(Airport sample) {
    DetachedCriteria query = DetachedCriteria.forClass(Airport.class);
    query.add(Restrictions.eq("iataCode", sample.getIataCode()));
    return (Airport) query.getExecutableCriteria(currentSession())
        .uniqueResult();
  }
View Full Code Here

TOP

Related Classes of org.hibernate.criterion.DetachedCriteria

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.