Example usage for org.hibernate.criterion Restrictions in

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

Introduction

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

Prototype

public static Criterion in(String propertyName, Collection values) 

Source Link

Document

Apply an "in" constraint to the named property.

Usage

From source file:com.evolveum.midpoint.repo.sql.QueryInterpreterTest.java

License:Apache License

@Test
public void inOidTest() throws Exception {
    Session session = open();//from  ww w . ja  va  2 s.  c o  m
    try {
        Criteria main = session.createCriteria(RObject.class, "o");
        main.add(Restrictions.in("oid", Arrays.asList("1", "2")));
        ProjectionList projections = Projections.projectionList();
        addFullObjectProjectionList("o", projections, false);
        main.setProjection(projections);

        String expected = HibernateToSqlTranslator.toSql(main);

        InOidFilter filter = InOidFilter.createInOid(Arrays.asList("1", "2"));

        ObjectQuery query = ObjectQuery.createObjectQuery(filter);
        String real = getInterpretedQuery(session, ObjectType.class, query, false);

        LOGGER.info("exp. query>\n{}\nreal query>\n{}", new Object[] { expected, real });
        AssertJUnit.assertEquals(expected, real);
    } finally {
        close(session);
    }
}

From source file:com.evolveum.midpoint.repo.sql.QueryInterpreterTest.java

License:Apache License

@Test
public void test350queryObjectClassTypeAbstractRole() throws Exception {
    Session session = open();//from   w  ww.ja  v a 2s  .c  o m

    try {
        Criteria main = session.createCriteria(RObject.class, "o");
        ProjectionList projections = Projections.projectionList();
        addFullObjectProjectionList("o", projections, false);
        main.setProjection(projections);

        List<RObjectType> list = new ArrayList<>();
        list.add(RObjectType.ABSTRACT_ROLE);
        list.add(RObjectType.ORG);
        list.add(RObjectType.ROLE);
        main.add(Restrictions.in("o." + RObject.F_OBJECT_TYPE_CLASS, list));
        String expected = HibernateToSqlTranslator.toSql(main);

        TypeFilter type = TypeFilter.createType(AbstractRoleType.COMPLEX_TYPE, null);
        String real = getInterpretedQuery(session, ObjectType.class, ObjectQuery.createObjectQuery(type));

        LOGGER.info("exp. query>\n{}\nreal query>\n{}", new Object[] { expected, real });
        AssertJUnit.assertEquals(expected, real);
    } finally {
        close(session);
    }
}

From source file:com.evolveum.midpoint.repo.sql.SqlRepositoryServiceImpl.java

License:Apache License

private List<RObject> deleteTransitiveHierarchy(RObject rObjectToModify, Session session)
        throws SchemaException, DtoTranslationException {

    Criteria cDescendant = session.createCriteria(ROrgClosure.class)
            .setProjection(Projections.property("descendant"))
            .add(Restrictions.eq("ancestor", rObjectToModify));

    Criteria cAncestor = session.createCriteria(ROrgClosure.class)
            .setProjection(Projections.property("ancestor")).createCriteria("ancestor", "anc")
            .add(Restrictions.and(Restrictions.eq("this.descendant", rObjectToModify),
                    Restrictions.not(Restrictions.eq("anc.oid", rObjectToModify.getOid()))));

    Criteria cOrgClosure = session.createCriteria(ROrgClosure.class);

    List<RObject> ocAncestor = cAncestor.list();
    List<RObject> ocDescendant = cDescendant.list();

    if (ocAncestor != null && !ocAncestor.isEmpty()) {
        cOrgClosure.add(Restrictions.in("ancestor", ocAncestor));
    } else {//from ww  w . ja  v a2 s  .  c  o  m
        LOGGER.trace("No ancestors for object: {}", rObjectToModify.getOid());
    }

    if (ocDescendant != null && !ocDescendant.isEmpty()) {
        cOrgClosure.add(Restrictions.in("descendant", ocDescendant));
    } else {
        LOGGER.trace("No descendants for object: {}", rObjectToModify.getOid());
    }

    List<ROrgClosure> orgClosure = cOrgClosure.list();

    for (ROrgClosure o : orgClosure) {
        if (LOGGER.isTraceEnabled()) {
            RObject ancestor = o.getAncestor();
            RObject descendant = o.getDescendant();
            LOGGER.trace("deleting from hierarchy: A:{} D:{} depth:{}", new Object[] {
                    RUtil.getDebugString(ancestor), RUtil.getDebugString(descendant), o.getDepth() });
        }
        session.delete(o);
    }
    deleteHierarchy(rObjectToModify, session);
    return ocDescendant;
}

From source file:com.floreantpos.model.dao.ShopTableDAO.java

License:Open Source License

public List<ShopTableType> getTableByTypes(List<ShopTableType> types) {
    List<Integer> typeIds = new ArrayList<Integer>();
    for (ShopTableType shopTableType : types) {
        typeIds.add(shopTableType.getId());
    }/*from ww  w  .  j av a  2 s.  co m*/

    Session session = getSession();
    Criteria criteria = session.createCriteria(ShopTable.class);
    criteria.createAlias("types", "t"); //$NON-NLS-1$ //$NON-NLS-2$
    criteria.add(Restrictions.in("t.id", typeIds)); //$NON-NLS-1$
    //criteria.add(Restrictions("t.id", typeIds)); //$NON-NLS-1$
    criteria.addOrder(Order.asc(ShopTable.PROP_ID));
    return criteria.list();
}

From source file:com.gisgraphy.domain.repository.OpenStreetMapDao.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
public OpenStreetMap getNearestByosmIds(final Point point, final List<Long> ids) {
    if (ids == null || ids.size() == 0) {
        return null;
    }/* www .  java  2 s.  co  m*/
    return (OpenStreetMap) this.getHibernateTemplate().execute(new HibernateCallback() {

        public Object doInHibernate(Session session) throws PersistenceException {

            Criteria criteria = session.createCriteria(OpenStreetMap.class);

            criteria.add(new DistanceRestriction(point, DEFAULT_DISTANCE, true));
            criteria.add(Restrictions.in("openstreetmapId", ids));

            String pointAsString = "ST_GeometryFromText('POINT(" + point.getX() + " " + point.getY() + ")',"
                    + SRID.WGS84_SRID.getSRID() + ")";
            String distanceCondition = new StringBuffer().append(DISTANCE_SPHERE_FUNCTION).append("(")
                    .append(pointAsString).append(",").append(SpatialProjection.ST_CLOSEST_POINT).append("(")
                    .append("this_.").append(OpenStreetMap.SHAPE_COLUMN_NAME).append(",").append(pointAsString)
                    .append(")").append(")").toString();
            criteria.addOrder(new NativeSQLOrder(distanceCondition));
            criteria = criteria.setMaxResults(1);
            criteria.setCacheable(true);
            // List<Object[]> queryResults =testCriteria.list();
            OpenStreetMap openStreetMap = (OpenStreetMap) criteria.uniqueResult();

            return openStreetMap;

        }
    });
}

From source file:com.github.dactiv.orm.core.hibernate.support.BasicHibernateDao.java

License:Apache License

/**
 * PK?.//  www .  ja  v  a2 s . c o m
 * 
 * @param ids ID?
 * 
 * @return List
 */
public List<T> get(Collection<PK> ids) {
    if (CollectionUtils.isEmpty(ids)) {
        return Collections.emptyList();
    }
    return createCriteria(Restrictions.in(getIdName(), ids)).list();
}

From source file:com.github.dactiv.orm.core.hibernate.support.BasicHibernateDao.java

License:Apache License

/**
 * PK?.
 * 
 * @param ids ID?
 * 
 * @return List
 */
public List<T> get(PK[] ids) {
    return createCriteria(Restrictions.in(getIdName(), ids)).list();
}

From source file:com.globalsight.everest.usermgr.UserManagerLocal.java

License:Apache License

/**
 * @see UserManager.getUserInfos(String)
 *///from  ww  w.  ja  va  2  s.  com
public List getUserInfos(String[] p_userIds) throws RemoteException, UserManagerException {
    List uIds = new ArrayList();
    for (String uId : p_userIds) {
        uIds.add(uId);
    }

    Session session = HibernateUtil.getSession();

    boolean filterUser = false;

    Criteria c = session.createCriteria(UserImpl.class);
    c.add(Restrictions.in("userId", uIds));
    c.add(Restrictions.not(Restrictions.eq("state", User.State.DEACTIVE)));
    c.add(Restrictions.not(Restrictions.eq("state", User.State.DELETED)));

    List<UserImpl> us = c.list();
    List userInfos = new ArrayList();
    for (UserImpl u : us) {
        userInfos.add(u.toUserInfo());
    }

    return userInfos;
}

From source file:com.globalsight.everest.usermgr.UserManagerLocal.java

License:Apache License

/**
 * @see UserManager.getUsersByFilter(String, Project)
 *//*  w  w  w  .  j a va2 s  .c om*/
public List getUsersByFilter(String p_roleName, Project p_project)
        throws RemoteException, UserManagerException {
    String[] userIds = getUserIdsByFilter(p_roleName, p_project);
    List users = new ArrayList();
    for (String id : userIds) {
        users.add(id);
    }

    Criteria c = HibernateUtil.getSession().createCriteria(UserImpl.class);
    c.add(Restrictions.in("userId", users));
    return c.list();

    // check out a connection from the connection pool
    //        DirContext dirContext = checkOutConnection(false);
    //        setConnectionOptions(dirContext);
    //        List users = null;
    //        try
    //        {
    //            users = getUsers(userIds, null, dirContext);
    //        }
    //        catch (NamingException ldp)
    //        {
    //            String[] errorMsgArg = new String[]
    //            { UserManagerException.ARG_FAILED_TO_GET_USERS_ENTRIES };
    //            CATEGORY.error(
    //                    "Failed to get all the users that match the filter - Role: "
    //                            + p_roleName + ", Project: " + p_project.getName()
    //                            + p_roleName + ", Project: " + p_project.getName(),
    //                    ldp);
    //            throw new UserManagerException(
    //                    UserManagerException.MSG_GET_USERS_ERROR, errorMsgArg, ldp);
    //        }
    //        finally
    //        {
    //            checkInConnection(dirContext);
    //        }
    //        return users;
}

From source file:com.globalsight.everest.usermgr.UserManagerLocal.java

License:Apache License

/**
 * Get users matched the specified criteria
 * /*from w w w.  j a  v a  2 s  .c  om*/
 * @param p_userAttrs
 *            - Arrtibute array contains the User entry attributes
 * @param p_roleAttrs
 *            - Attribute array contains the Role entry attributes
 * @param p_project
 * @return a Vector of User objects
 * @exception UserManagerException
 *                - Component related exception.
 * @exception java.rmi.RemoteException
 *                - Network related exception.
 */
public Vector getUsers(UserSearchParams p_searchParams, Project p_project)
        throws RemoteException, UserManagerException {
    Session session = HibernateUtil.getSession();

    boolean filterUser = false;
    Vector<UserImpl> us = new Vector<UserImpl>();

    Criteria c = session.createCriteria(UserImpl.class);
    String userId = p_searchParams.getIdName();
    if (userId != null && userId.length() > 0) {
        filterUser = true;
        c.add(Restrictions.or(Restrictions.ilike("userId", "%" + userId + "%"),
                Restrictions.ilike("userName", "%" + userId + "%")));
    }

    String firstName = p_searchParams.getFirstName();
    if (firstName != null && firstName.length() > 0) {
        filterUser = true;
        c.add(Restrictions.eq("firstName", firstName));
    }

    String lastName = p_searchParams.getLastName();
    if (lastName != null && lastName.length() > 0) {
        filterUser = true;
        c.add(Restrictions.eq("lastName", lastName));
    }

    String email = p_searchParams.getEmail();
    if (email != null && email.length() > 0) {
        filterUser = true;
        c.add(Restrictions.eq("email", email));
    }

    if (filterUser) {
        us.addAll(c.list());
    }

    boolean filterRole = false;
    Criteria cc = session.createCriteria(ContainerRoleImpl.class);
    Criteria uc = session.createCriteria(UserRoleImpl.class);

    String sourceLocale = p_searchParams.getSourceLocaleParam();
    if (sourceLocale != null && sourceLocale.length() > 0) {
        filterRole = true;
        cc.add(Restrictions.eq("sourceLocale", sourceLocale));
        uc.add(Restrictions.eq("sourceLocale", sourceLocale));
    }

    String targetLocale = p_searchParams.getTargetLocaleParam();
    if (targetLocale != null && targetLocale.length() > 0) {
        filterRole = true;
        cc.add(Restrictions.eq("targetLocale", targetLocale));
        uc.add(Restrictions.eq("targetLocale", targetLocale));
    }

    if (filterRole) {
        List uids = new ArrayList();

        cc.add(Restrictions.eq("state", User.State.ACTIVE));
        uc.add(Restrictions.eq("state", User.State.ACTIVE));

        List<ContainerRoleImpl> crs = cc.list();
        List<UserRoleImpl> urs = uc.list();

        for (ContainerRoleImpl cr : crs) {
            uids.addAll(cr.getUserIds());
        }

        for (UserRoleImpl ur : urs) {
            uids.add(ur.getUser());
        }

        if (uids.size() > 0) {
            c = session.createCriteria(UserImpl.class);
            c.add(Restrictions.in("userId", uids));

            us.addAll(c.list());
        }
    }

    return us;
    //        return getUsers(p_userAttrs, p_roleAttrs, null, p_project);
}