Example usage for org.hibernate.criterion Restrictions isNull

List of usage examples for org.hibernate.criterion Restrictions isNull

Introduction

In this page you can find the example usage for org.hibernate.criterion Restrictions isNull.

Prototype

public static Criterion isNull(String propertyName) 

Source Link

Document

Apply an "is null" constraint to the named property

Usage

From source file:com.lyh.licenseworkflow.dao.EnhancedHibernateDaoSupport.java

/**
 * ?? from DeviceResource where type = 'ROUTER' and temp = false;
 *
 * @param propertyNames ???//  w w w .jav  a 2  s .c  om
 * @param values        
 * @return ??
 */
@SuppressWarnings("unchecked")
public List<T> getEntitiesByPropNames(final String[] propertyNames, final Object[] values) {
    if (ArrayUtils.isEmpty(propertyNames) || ArrayUtils.isEmpty(values)
            || propertyNames.length != values.length) {
        throw new IllegalArgumentException("arguments is invalid.");
    }
    return (List<T>) getHibernateTemplate().execute(new HibernateCallback() {

        @Override
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Criteria c = session.createCriteria(getEntityName());
            for (int i = 0; i < propertyNames.length; i++) {
                String propertyName = propertyNames[i];
                if (propertyName.indexOf(".") != -1) {
                    Criteria subC = null;
                    String[] props = StringUtils.split(propertyName, ".");
                    for (int j = 0; j < props.length; j++) {
                        if (j != props.length - 1) {
                            subC = c.createCriteria(props[j]);
                        }
                    }
                    if (values[i] == null)
                        subC.add(Restrictions.isNull(propertyName.substring(propertyName.indexOf(".") + 1)));
                    else
                        subC.add(Restrictions.eq(propertyName.substring(propertyName.indexOf(".") + 1),
                                values[i]));
                } else {
                    if (values[i] == null)
                        c.add(Restrictions.isNull(propertyNames[i]));
                    else if (values[i].toString().indexOf("%") != -1) {// ,?value?%
                        c.add(Restrictions.like(propertyNames[i], values[i]));
                    } else {
                        c.add(Restrictions.eq(propertyNames[i], values[i]));
                    }
                }
            }
            return c.list();
        }
    });
}

From source file:com.lyh.licenseworkflow.dao.EnhancedHibernateDaoSupport.java

/**
 * ??? from DeviceResource where type = 'ROUTER' and temp = false;
 *
 * @param propertyNames ???//from   w ww .j  a va2  s  .  c o  m
 * @param values        
 * @return ??
 */
@SuppressWarnings("unchecked")
public int countEntitiesByPropNames(final String[] propertyNames, final Object[] values) {
    if (ArrayUtils.isEmpty(propertyNames) || ArrayUtils.isEmpty(values)
            || propertyNames.length != values.length) {
        throw new IllegalArgumentException("arguments is invalid.");
    }
    return (Integer) getHibernateTemplate().execute(new HibernateCallback() {

        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Criteria c = session.createCriteria(getEntityName());
            for (int i = 0; i < propertyNames.length; i++) {
                String propertyName = propertyNames[i];
                if (propertyName.indexOf(".") != -1) {
                    Criteria subC = null;
                    String[] props = StringUtils.split(propertyName, ".");
                    for (int j = 0; j < props.length; j++) {
                        if (j != props.length - 1) {
                            subC = c.createCriteria(props[j]);
                        }
                    }
                    if (values[i] == null)
                        subC.add(Restrictions.isNull(propertyName.substring(propertyName.indexOf(".") + 1)));
                    else
                        subC.add(Restrictions.eq(propertyName.substring(propertyName.indexOf(".") + 1),
                                values[i]));
                } else {
                    if (values[i] == null)
                        c.add(Restrictions.isNull(propertyNames[i]));
                    else
                        c.add(Restrictions.eq(propertyNames[i], values[i]));
                }
            }
            int num = ((Integer) c.setProjection(Projections.rowCount()).uniqueResult()).intValue();// ???
            return new Integer(num);
        }
    });
}

From source file:com.lyh.licenseworkflow.dao.EnhancedHibernateDaoSupport.java

/**
 * ?? from DeviceResource where type = 'ROUTER' and temp = false;
 *
 * @param start         ?//w w  w.  j  a  v  a  2 s  .com
 * @param pageSize      ??
 * @param propertyNames ???
 * @param values        
 * @return ??
 */
@SuppressWarnings("unchecked")
public List<T> getPagingEntitiesByPropNames(final int start, final int pageSize, final String[] propertyNames,
        final Object[] values) {
    if (ArrayUtils.isEmpty(propertyNames) || ArrayUtils.isEmpty(values)
            || propertyNames.length != values.length) {
        throw new IllegalArgumentException("arguments is invalid.");
    }
    return (List<T>) getHibernateTemplate().execute(new HibernateCallback() {

        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Criteria c = session.createCriteria(getEntityName());
            c.setFirstResult(start);
            c.setMaxResults(pageSize);
            for (int i = 0; i < propertyNames.length; i++) {
                String propertyName = propertyNames[i];
                if (propertyName.indexOf(".") != -1) {
                    Criteria subC = null;
                    String[] props = StringUtils.split(propertyName, ".");
                    for (int j = 0; j < props.length; j++) {
                        if (j != props.length - 1) {
                            subC = c.createCriteria(props[j]);
                        }
                    }
                    if (values[i] == null)
                        subC.add(Restrictions.isNull(propertyName.substring(propertyName.indexOf(".") + 1)));
                    else
                        subC.add(Restrictions.eq(propertyName.substring(propertyName.indexOf(".") + 1),
                                values[i]));
                } else {
                    if (values[i] == null)
                        c.add(Restrictions.isNull(propertyNames[i]));
                    else if (values[i].toString().indexOf("%") != -1) {// ,?value?%
                        c.add(Restrictions.like(propertyNames[i], values[i]));
                    } else {
                        c.add(Restrictions.eq(propertyNames[i], values[i]));
                    }
                }
            }
            return c.list();
        }
    });
}

From source file:com.maydesk.base.dao.DaoRole.java

License:Mozilla Public License

public static List<MUserRole> getRoles(MUser user, MBase context, Session... session2) {
    Session session = null;/*from ww  w  . j  av  a 2s  .co m*/
    if (session2 != null && session2.length > 0) {
        session = session2[0];
    } else {
        session = PDHibernateFactory.getSession();
    }
    Criteria criteria = session.createCriteria(MUserRole.class);
    criteria.add(eq("userRef", user));
    if (context == null) {
        criteria.add(Restrictions.isNull("contextClass"));
    } else {
        Disjunction orCondition = Restrictions.disjunction();
        criteria.add(orCondition);
        Conjunction andCondition = Restrictions.conjunction();
        orCondition.add(andCondition);
        andCondition.add(eq("contextId", context.getId()));
        andCondition.add(eq("contextClass", context.getClass().getCanonicalName()));
        orCondition.add(Restrictions.isNull("contextClass"));

    }
    return criteria.list();
}

From source file:com.mec.DAO.Postgre.EstablecimientoPostgreDAO.java

public List<EstablecimientoPost> getAll() {
    Criteria cr = this.getSessionPostgre().createCriteria(EstablecimientoPost.class);
    cr.add(Restrictions.isNull("fechaBaja"));
    return lazyInit(cr.list());
}

From source file:com.metropolitan.formulasport727.dao.KlasifikacijaDAOImpl.java

@Override
public List<Klasifikacija> getListaSvihKlasifikacijaSezone(Sezona sezona) {
    return session.createCriteria(Klasifikacija.class).add(Restrictions.isNull("vozId"))
            .add(Restrictions.isNull("timId")).add(Restrictions.eq("sezId", sezona)).addOrder(Order.asc("id"))
            .list();/*from  w  w  w  .j a  v  a  2  s  . c om*/
}

From source file:com.opengamma.util.db.HibernateDbUtils.java

License:Open Source License

/**
 * Builds a Hibernate query.//from w w  w  .  j  av a2  s . co m
 * 
 * @param propertyName  the property name
 * @param value  the value
 * @return the criterion, not null
 */
public static Criterion eqOrIsNull(String propertyName, Object value) {
    if (value == null) {
        return Restrictions.isNull(propertyName);
    } else {
        return Restrictions.eq(propertyName, value);
    }
}

From source file:com.ponysdk.hibernate.query.decorator.AbstractCriteriaDecorator.java

License:Apache License

@SuppressWarnings("rawtypes")
@Override/*from  w ww  .ja  v  a2s .c o m*/
public void render(final CriteriaContext context) {
    final Criterion field = context.getCriterion();
    Criteria criteria = context.getOrderingCriteria();

    final List<String> propertyNamePath = Arrays.asList(field.getPojoProperty().split(REGEX_SPLIT));
    final Iterator<String> iter = propertyNamePath.iterator();
    String key = null;
    String associationPath = null;
    if (propertyNamePath.size() == 1) {
        associationPath = iter.next();
    } else
        while (iter.hasNext()) {
            key = iter.next();
            if (associationPath == null) {
                associationPath = new String(key);
            } else {
                associationPath += "." + key;
            }
            if (iter.hasNext()) {
                criteria = criteria.createCriteria(associationPath, key, CriteriaSpecification.INNER_JOIN);
                associationPath = new String(key);
            }
        }

    final T value = getObjectValue(field);
    ComparatorType comparator = field.getComparator();

    if (value != null) {
        if (value.toString().contains("%")) {
            comparator = ComparatorType.LIKE;
        }
    }

    if (field.getValue() != null || field.getComparator() == ComparatorType.IS_NULL
            || field.getComparator() == ComparatorType.IS_NOT_NULL) {

        switch (comparator) {
        case EQ:
            criteria.add(Restrictions.eq(associationPath, value));
            break;
        case GE:
            criteria.add(Restrictions.ge(associationPath, value));
            break;
        case GT:
            criteria.add(Restrictions.gt(associationPath, value));
            break;
        case LE:
            criteria.add(Restrictions.le(associationPath, value));
            break;
        case LT:
            criteria.add(Restrictions.lt(associationPath, value));
            break;
        case NE:
            criteria.add(Restrictions.ne(associationPath, value));
            break;
        case LIKE:
            criteria.add(Restrictions.ilike(associationPath, value));
            break;
        case IS_NULL:
            criteria.add(Restrictions.isNull(associationPath));
            break;
        case IS_NOT_NULL:
            criteria.add(Restrictions.isNotNull(associationPath));
            break;
        case IN:
            if (value instanceof Collection) {
                criteria.add(Restrictions.in(associationPath, (Collection) value));
            } else if (value instanceof Object[]) {
                criteria.add(Restrictions.in(associationPath, (Object[]) value));
            } else {
                log.warn("Type not allowed for IN clause: " + value.getClass() + ", value: " + value);
            }
            break;

        default:
            log.warn("Restriction not supported: " + comparator);
            break;
        }
    }

    switch (field.getSortingType()) {
    case ASCENDING:
        criteria.addOrder(Order.asc(associationPath));
        break;
    case DESCENDING:
        criteria.addOrder(Order.desc(associationPath));
        break;
    case NONE:
        break;
    }

}

From source file:com.prueba.spring.dao.impl.EventoDAO.java

@Transactional(readOnly = true)
public RespuestaGenerica<List<Evento>> obtenerEventosSinColaborador(int idColaborador) {
    RespuestaGenerica<List<Evento>> respuesta;
    try {//from   w  w  w  .j a va 2  s  .  c o m
        this.iniciaOperacion();
        Criteria criteria = session.createCriteria(Evento.class);
        criteria.createAlias("colaboradores", "c", JoinType.LEFT_OUTER_JOIN).add(Restrictions
                .or(Restrictions.ne("c.idColaborador", idColaborador), Restrictions.isNull("c.idColaborador")));
        List<Evento> eventos = criteria.list();
        respuesta = new RespuestaGenerica<List<Evento>>(eventos);
    } catch (Exception ex) {
        Logger.getLogger(EventoDAO.class.getName()).log(Level.SEVERE, null, ex);
        respuesta = new RespuestaGenerica(ex);
    } finally {
        try {
            session.close();
        } catch (Exception ex) {
            Logger.getLogger(EventoDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return respuesta;
}

From source file:com.puertobahia.iceberg.dao.impl.ZonaDAOImpl.java

@Override
public Zona getById(Long id) {
    Criteria crit = getSession().createCriteria(Zona.class);
    crit.add(Restrictions.idEq(id));//from www. ja va 2 s . com
    crit.setFetchMode("usuario", FetchMode.JOIN);
    crit.setFetchMode("usuario.empleado", FetchMode.JOIN);
    crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    crit.setFetchMode("consejos_comunitario", FetchMode.JOIN);
    crit.createAlias("consejos_comunitario", "consejo", JoinType.LEFT_OUTER_JOIN);
    crit.add(Restrictions.or(Restrictions.and(Restrictions.eq("consejo.estado", 0)),
            Restrictions.isNull("consejo.estado")));
    return (Zona) crit.uniqueResult();
    /*Criteria crit = getSession().createCriteria(Zona.class);
     crit.add(Restrictions.idEq(id));
     crit.setFetchMode("usuario", FetchMode.JOIN);
     crit.setFetchMode("usuario.empleado", FetchMode.JOIN);
     crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
     Zona zona = (Zona) crit.uniqueResult();
     Criteria crit2 = getSession().createCriteria(ConsejoComunitario.class);
     zona.setConsejos_comunitario(crit2.add(Restrictions.and(Restrictions.idEq(zona.getId()),Restrictions.eq("estado", 0))).list());
     return zona;*/
}