Java 类javax.persistence.criteria.CriteriaBuilder 实例源码

项目:marathonv5    文件:LiveSalesListFacadeREST.java   
@GET
@Produces({"application/xml", "application/json"})
@Path("/recent/region/{regionName}/{orderLineId}")
public List<LiveSalesList> findRecentRegionFrom(@PathParam("regionName") String regionName, @PathParam("orderLineId") Integer orderLineId) {
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    javax.persistence.criteria.CriteriaQuery cq = cb.createQuery();
    Root<LiveSalesList> liveSalesList = cq.from(LiveSalesList.class);
    cq.select(liveSalesList);
    cq.where(cb.and(
        cb.equal(liveSalesList.get(LiveSalesList_.region), regionName),
        cb.gt(liveSalesList.get(LiveSalesList_.orderLineId), orderLineId)
    ));
    Query q = getEntityManager().createQuery(cq);
    q.setMaxResults(500);
    return q.getResultList();
}
项目:owl    文件:TestSuiteFilterSpecification.java   
@Override
public Predicate toPredicate(Root<TestSuite> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
    Predicate result = null;

    if (StringUtils.isNotEmpty(filter.getSuite())) {
        result = criteriaBuilder.like(criteriaBuilder.lower(root.get(SUITE_PROPERTY)),
                buildLikeValue(filter.getSuite()));
    }

    return result;
}
项目:plumdo-work    文件:SimpleExpression.java   
@SuppressWarnings({ "rawtypes", "unchecked" })  
public Predicate toPredicate(Root<?> root, CriteriaQuery<?> query,  
        CriteriaBuilder builder) {  
    Path expression = null;  
    if(fieldName.contains(".")){  
        String[] names = StringUtils.split(fieldName, ".");  
        expression = root.get(names[0]);  
        for (int i = 1; i < names.length; i++) {  
            expression = expression.get(names[i]);  
        }  
    }else{  
        expression = root.get(fieldName);  
    }  

    switch (operator) {  
    case EQ:  
        return builder.equal(expression, value);  
    case NE:  
        return builder.notEqual(expression, value);  
    case LIKE:  
        return builder.like((Expression<String>) expression, "%" + value + "%");  
    case LT:  
        return builder.lessThan(expression, (Comparable) value);  
    case GT:  
        return builder.greaterThan(expression, (Comparable) value);  
    case LTE:  
        return builder.lessThanOrEqualTo(expression, (Comparable) value);  
    case GTE:  
        return builder.greaterThanOrEqualTo(expression, (Comparable) value);  
    default:  
        return null;  
    }  
}
项目:otus_java_2017_10    文件:ConnectionHelper.java   
private static void _criteria(DbService dbService) {
    final EntityManager em = dbService.getEntityManager();

    // INSERT new record
    em.getTransaction().begin();
    em.persist(new Account("A"));
    em.persist(new Account("B"));
    em.persist(new Account("C"));
    em.getTransaction().commit();



    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Account> query = builder.createQuery(Account.class);
    Root<Account> acc = query.from(Account.class);

    Predicate cond = builder.gt(acc.get("id"), 1);
    query.where(cond);
    TypedQuery<Account> q = em.createQuery(query);
    List<Account> resultList = q.getResultList();
    System.out.println(resultList);


}
项目:spring-microservice-sample    文件:PostSpecifications.java   
public static Specification<Post> filterByKeywordAndStatus(
    final String keyword,//
    final Post.Status status) {
    return (Root<Post> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
        List<Predicate> predicates = new ArrayList<>();
        if (StringUtils.hasText(keyword)) {
            predicates.add(
                cb.or(
                    cb.like(root.get(Post_.title), "%" + keyword + "%"),
                    cb.like(root.get(Post_.content), "%" + keyword + "%")
                )
            );
        }

        if (status != null) {
            predicates.add(cb.equal(root.get(Post_.status), status));
        }

        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    };
}
项目:amanda    文件:AbstractJpaCriterionRepository.java   
@Override
public Page search(QueryCriteria criteria, Pageable pageable) {
    CriteriaBuilder builder = this.entityManager.getCriteriaBuilder();

    CriteriaQuery<Long> countCriteria = builder.createQuery(Long.class);
    Root<T> countRoot = countCriteria.from(this.domainClass);
    long total = this.entityManager.createQuery(
            countCriteria.select(builder.count(countRoot))
                    .where(toPredicates(criteria, countRoot, builder))
    ).getSingleResult();

    CriteriaQuery<T> pageCriteria = builder.createQuery(this.domainClass);
    Root<T> pageRoot = pageCriteria.from(this.domainClass);
    List<T> list = this.entityManager.createQuery(
            pageCriteria.select(pageRoot)
                    .where(toPredicates(criteria, pageRoot, builder))
                    .orderBy(toOrders(pageable.getSort(), pageRoot, builder))
    ).setFirstResult(pageable.getOffset())
            .setMaxResults(pageable.getPageSize())
            .getResultList();

    return new PageImpl<>(new ArrayList<>(list), pageable, total);
}
项目:bibliometrics    文件:RolePermissionDAO.java   
/**
 * retrieves the <code>RolesPermission</code> by the role.
 * 
 * @param role
 *            the role
 * @return userPermissions the list of permissions of the user
 * 
 */
public static Set<String> getPermission(String role) {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("userData");
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    tx.begin();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<RolePermission> q = cb.createQuery(RolePermission.class);
    Root<RolePermission> c = q.from(RolePermission.class);
    q.select(c).where(cb.equal(c.get("roleName"), role));
    TypedQuery<RolePermission> query = em.createQuery(q);
    List<RolePermission> permissions = query.getResultList();
    Set<String> userPermissions = new HashSet<String>();
    for (RolePermission permission : permissions)
        userPermissions.add(permission.getPermission());
    tx.commit();
    em.close();
    return userPermissions;
}
项目:osc-core    文件:PodEntityMgr.java   
public static Pod findExternalId(EntityManager em, String externalId) {

        CriteriaBuilder cb = em.getCriteriaBuilder();

        CriteriaQuery<Pod> query = cb.createQuery(Pod.class);

        Root<Pod> root = query.from(Pod.class);

        query = query.select(root)
                .where(cb.equal(root.get("externalId"), externalId));

        try {
            return em.createQuery(query).getSingleResult();
        } catch (NoResultException nre) {
            return null;
        }
    }
项目:marathonv5    文件:LiveSalesListFacadeREST.java   
@GET
@Produces({"application/xml", "application/json"})
@Path("/recent/producttype/{id}/{orderLineId}")
public List<LiveSalesList> findRecentProductTypeFrom(@PathParam("id") Integer productTypeId, @PathParam("orderLineId") Integer orderLineId) {
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    javax.persistence.criteria.CriteriaQuery cq = cb.createQuery();
    Root<LiveSalesList> liveSalesList = cq.from(LiveSalesList.class);
    cq.select(liveSalesList);
    cq.where(cb.and(
        cb.equal(liveSalesList.get(LiveSalesList_.productTypeId), productTypeId),
        cb.gt(liveSalesList.get(LiveSalesList_.orderLineId), orderLineId)
    ));
    Query q = getEntityManager().createQuery(cq);
    q.setMaxResults(500);
    return q.getResultList();
}
项目:marathonv5    文件:LiveSalesListFacadeREST.java   
@GET
@Produces({"application/xml", "application/json"})
@Path("/recent/region/producttype/{regionName}/{productTypeId}")
public List<LiveSalesList> findRecentRegionProductType(@PathParam("regionName") String regionName, @PathParam("productTypeId") Integer productTypeId) {
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    javax.persistence.criteria.CriteriaQuery cq = cb.createQuery();
    Root<LiveSalesList> liveSalesList = cq.from(LiveSalesList.class);
    cq.select(liveSalesList);
    cq.where(cb.and(
            cb.equal(liveSalesList.get(LiveSalesList_.productTypeId), productTypeId), 
            cb.equal(liveSalesList.get(LiveSalesList_.region), regionName)
    ));
    Query q = getEntityManager().createQuery(cq);
    q.setMaxResults(500);
    return q.getResultList();
}
项目:marathonv5    文件:LiveSalesListFacadeREST.java   
@GET
@Produces({"application/xml", "application/json"})
@Path("/recent/region/producttype/{regionName}/{productTypeId}")
public List<LiveSalesList> findRecentRegionProductType(@PathParam("regionName") String regionName, @PathParam("productTypeId") Integer productTypeId) {
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    javax.persistence.criteria.CriteriaQuery cq = cb.createQuery();
    Root<LiveSalesList> liveSalesList = cq.from(LiveSalesList.class);
    cq.select(liveSalesList);
    cq.where(cb.and(
            cb.equal(liveSalesList.get(LiveSalesList_.productTypeId), productTypeId), 
            cb.equal(liveSalesList.get(LiveSalesList_.region), regionName)
    ));
    Query q = getEntityManager().createQuery(cq);
    q.setMaxResults(500);
    return q.getResultList();
}
项目:spring-repository-plus    文件:SpecificationImpl.java   
@Override
public Predicate toPredicate(Root<Object> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
    List<Predicate> predicates = new ArrayList<>();
    for(Specification specification: specifications){
        Predicate p = specification.toPredicate(root, cq, cb);
        if(p!=null)
            predicates.add(p);
    }
    return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}
项目:cr-private-server    文件:ClanService.java   
public List<ClanEntity> search(String name, int minMembers, int maxMembers, int minTrophies, boolean onlyJoinable) {
    try (Session session = session()) {
        CriteriaBuilder builder = session.getCriteriaBuilder();
        CriteriaQuery<ClanEntity> query = builder.createQuery(ClanEntity.class);
        Root<ClanEntity> root = query.from(ClanEntity.class);
        query.select(root);

        if (name != null && !name.isEmpty()) {
            query.where(builder.like(root.get("name"), "%" + name + "%"));
        }

        // TODO: Check min and max members

        if (minTrophies != 0) {
            query.where(builder.greaterThan(root.get("score"), minTrophies));
        }

        if (onlyJoinable) {
            query.where(builder.equal(root.get("type"), builder.literal(ClanType.OPEN)));
            // TODO: Check members
        }

        return session.createQuery(query).getResultList();
    }
}
项目:osc-core    文件:ApplianceEntityMgr.java   
public static Appliance findByModel(EntityManager em, String model) {
    CriteriaBuilder cb = em.getCriteriaBuilder();

    CriteriaQuery<Appliance> query = cb.createQuery(Appliance.class);

    Root<Appliance> root = query.from(Appliance.class);

    query = query.select(root)
        .where(cb.equal(root.get("model"), model));

    try {
        return em.createQuery(query).getSingleResult();
    } catch (NoResultException nre) {
        return null;
    }
}
项目:photoiff    文件:PerfilService.java   
public Pessoa validarUsuario(String log, String pass){
    final CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();

    final CriteriaQuery<Pessoa> cquery = cb.createQuery(Pessoa.class);
    final Root<Pessoa> root = cquery.from(Pessoa.class);
    final List<Predicate> condicoes = new ArrayList<Predicate>();

    condicoes.add(cb.equal(root.get("usuario").get("login"), log));
    condicoes.add(cb.equal(root.get("usuario").get("senha"), pass));

    cquery.select(root).where(condicoes.toArray(new Predicate[]{}));
    Pessoa pessoa = new Pessoa();
    try{
        pessoa = getEntityManager().createQuery(cquery).getSingleResult();
    } catch (Exception e) {
        throw new QueryTimeoutException("Usuário ou senha invalido!");
    }   

    return pessoa;
}
项目:chr-krenn-fhj-ws2017-sd17-pse    文件:CommunityDAOImpl.java   
@Override
public Community findByName(String name) {
    LOG.info("findByName(name = " + name + ")");
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Community> criteria = builder.createQuery(Community.class);
    Root<Community> community = criteria.from(Community.class);
    criteria.where(builder.equal(community.get("name"), name));
    TypedQuery<Community> query = em.createQuery(criteria);
    try {
        Community c = query.getSingleResult();
        return initializeCom(c);
    } catch (NoResultException e) {
        LOG.error(e.toString());
        return null;
    }
}
项目:osc-core    文件:VirtualizationConnectorEntityMgr.java   
public static boolean isControllerTypeUsed(String controllerType, EntityManager em) {

        Long count = 0L;
        try {
            CriteriaBuilder cb = em.getCriteriaBuilder();

            CriteriaQuery<Long> query = cb.createQuery(Long.class);

            Root<VirtualizationConnector> root = query.from(VirtualizationConnector.class);

            query = query.select(cb.count(root))
                    .where(cb.equal(root.get("controllerType"), controllerType));

            count = em.createQuery(query).getSingleResult();
        } catch (Exception e) {
            // Ignore this exception
        }

        return count > 0;
    }
项目:bootstrap    文件:PaginationDao.java   
/**
 * Apply ordering criteria.
 */
private <T> void applyOrder(final UiPageRequest uiPageRequest, final Map<String, String> mapping, final CriteriaBuilder builder,
        final CriteriaQuery<T> query, final Root<T> root) {
    // Apply the sort
    if (uiPageRequest.getUiSort() != null) {

        // Need to order the result
        final UiSort uiSort = uiPageRequest.getUiSort();
        final String ormColumn = mapping.get(uiSort.getColumn());
        if (ormColumn != null) {

            // ORM column is validated
            final Sort sort = new Sort(uiSort.getDirection(), mapping.get(uiSort.getColumn()));
            query.orderBy(QueryUtils.toOrders(sort, root, builder));
        }
    }
}
项目:spring-data-examples    文件:CustomerSpecifications.java   
/**
 * All customers with an {@link Account} expiring before the given date.
 * 
 * @param date
 * @return
 */
public static Specification<Customer> accountExpiresBefore(final LocalDate date) {

    return new Specification<Customer>() {

        @Override
        public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

            Root<Account> accounts = query.from(Account.class);
            Path<Date> expiryDate = accounts.<Date> get("expiryDate");
            Predicate customerIsAccountOwner = cb.equal(accounts.<Customer> get("customer"), root);
            Predicate accountExpiryDateBefore = cb.lessThan(expiryDate, date.toDateTimeAtStartOfDay().toDate());

            return cb.and(customerIsAccountOwner, accountExpiryDateBefore);
        }
    };
}
项目:security-mgr-sample-plugin    文件:IsmPolicyApi.java   
@Override
public PolicyEntity getPolicy(String policyId, String domainId) throws Exception {

    return this.txControl.supports(new Callable<PolicyEntity>() {

        @Override
        public PolicyEntity call() throws Exception {

            CriteriaBuilder criteriaBuilder = IsmPolicyApi.this.em.getCriteriaBuilder();
            CriteriaQuery<PolicyEntity> query = criteriaBuilder.createQuery(PolicyEntity.class);
            Root<PolicyEntity> r = query.from(PolicyEntity.class);
            query.select(r)
                    .where(criteriaBuilder.and(
                            criteriaBuilder.equal(r.get("domain").get("id"), Long.parseLong(domainId)),
                            criteriaBuilder.equal(r.get("id"), Long.parseLong(policyId))));
            List<PolicyEntity> result = IsmPolicyApi.this.em.createQuery(query).getResultList();
            if (result.isEmpty()) {
                throw new Exception("Policy or Domain Entity does not exists...");
                //TODO - Add 404 error response - Sudhir
            }
            return result.get(0);
        }
    });
}
项目:chr-krenn-fhj-ws2017-sd17-pse    文件:CommunityDAOImpl.java   
@Override
public List<Community> findApprovedCommunities() {
    LOG.info("findApprovedCommunites()");
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Community> criteria = builder.createQuery(Community.class);
    Root<Community> community = criteria.from(Community.class);
    try {
        criteria.where(builder.equal(community.get("state"), new Enumeration(2)));
    } catch (DatabaseException e1) {
        LOG.error("Enumeration(2).APPROVED konnte nicht erstellt werden!");
    }
    TypedQuery<Community> query = em.createQuery(criteria);
    try {
        List <Community> coms = query.getResultList();
        for(Community c : coms) {
            initializeCom(c);
        }
        return coms;
    } catch (NoResultException e) {
        LOG.error(e.toString());
        return null;
    }
}
项目:security-mgr-sample-plugin    文件:IsmSecurityGroupApi.java   
@Override
public ManagerSecurityGroupElement getSecurityGroupById(String mgrSecurityGroupId) throws Exception {
    if (mgrSecurityGroupId == null) {
        return null;
    }
    DeviceEntity device = this.validationUtil.getDeviceOrThrow(this.vs.getMgrId());

    return this.txControl.supports(() -> {
        CriteriaBuilder cb = IsmSecurityGroupApi.this.em.getCriteriaBuilder();
        CriteriaQuery<SecurityGroupEntity> query = cb.createQuery(SecurityGroupEntity.class);
        Root<SecurityGroupEntity> root = query.from(SecurityGroupEntity.class);

        query.select(root).where(cb.equal(root.get("id"), Long.valueOf(mgrSecurityGroupId)),
                cb.equal(root.get("device"), device));

        SecurityGroupEntity result = null;
        try {
            result = IsmSecurityGroupApi.this.em.createQuery(query).getSingleResult();
        } catch (NoResultException e) {
            LOG.error(String.format("Cannot find Security group with id %s under device %s", mgrSecurityGroupId,
                    device.getId()));
        }
        return result;
    });
}
项目:aws-photosharing-example    文件:UserFacade.java   
public User findUser(String p_username) {
    CriteriaBuilder builder = em().getCriteriaBuilder();
    CriteriaQuery<User> criteria = builder.createQuery(User.class );
    Root<User> user_root = criteria.from(User.class);
    criteria.select(user_root);
    criteria.where(builder.equal(user_root.get("userName"), p_username));
    try {
        User u =  em().createQuery(criteria).getSingleResult();
        return u;
    } catch (NoResultException ex) {            
        return null;
    }       
}
项目:C4SG-Obsolete    文件:UserSpecification.java   
@Override
public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
    Predicate resultPredicate = null;
    List<Predicate> predicates = buildPredicates(root, cb);
    if (!predicates.isEmpty()) {
        resultPredicate = cb.and(predicates.toArray(new Predicate[predicates.size()]));
    }

    return resultPredicate;
}
项目:cloud    文件:ByRangeSpecification.java   
private Predicate buildRangePredicate(Range<T> range, Root<T> root, CriteriaBuilder builder) {
    if (range.isBetween()) {
        return builder.between(root.get(range.getField()), range.getFrom(), range.getTo());
    } else if (range.isFromSet()) {
        return builder.greaterThanOrEqualTo(root.get(range.getField()), range.getFrom());
    } else if (range.isToSet()) {
        return builder.lessThanOrEqualTo(root.get(range.getField()), range.getTo());
    }
    return null;
}
项目:osc-core    文件:SecurityGroupEntityMgr.java   
public static List<SecurityGroup> listOtherSecurityGroupsWithSameNetworkElementID(EntityManager em,
        SecurityGroup sg) {
    CriteriaBuilder cb = em.getCriteriaBuilder();

    CriteriaQuery<SecurityGroup> query = cb.createQuery(SecurityGroup.class);

    Root<SecurityGroup> root = query.from(SecurityGroup.class);
    query = query.select(root).where(cb.equal(root.get("networkElementId"), sg.getNetworkElementId()),
            cb.equal(root.get("projectId"), sg.getProjectId()), cb.notEqual(root, sg));

    List<SecurityGroup> list = em.createQuery(query).getResultList();
    return list;
}
项目:c4sg-services    文件:UserSpecification.java   
private List<Predicate> buildPredicates(Root<User> root, CriteriaBuilder cb) {
    List<Predicate> predicates = new ArrayList<>();
    conditions.forEach((k, v) -> {
        if (Optional.ofNullable(v).isPresent()) {
            predicates.add(cb.like(root.get(k), "%" + String.valueOf(v.toString()) + "%"));
        }
    });
    return predicates;
}
项目:datatable-java    文件:DatatableDAOImpl.java   
private long countDefault(final Specification<T> specification, final DatatableQuery<?, T> input) {
    final EntityManager entityManager = entityManagerFactory.createEntityManager();
      final CriteriaBuilder qb = entityManager.getCriteriaBuilder();
      final CriteriaQuery<Long> cq = qb.createQuery(Long.class);
      final Root<T> from = cq.from(this.entity);

      cq.select(qb.count(from));
      if (specification != null) {
          cq.where(specification.toPredicate(from, cq, qb));
      }
      final long ret = entityManager.createQuery(cq).getSingleResult();
      entityManager.close();
return ret;
  }
项目:otus_java_2017_06    文件:UserDataSetDAO.java   
public UserDataSet readByName(String name) {
    CriteriaBuilder builder = session.getCriteriaBuilder();
    CriteriaQuery<UserDataSet> criteria = builder.createQuery(UserDataSet.class);
    Root<UserDataSet> from = criteria.from(UserDataSet.class);
    criteria.where(builder.equal(from.get("name"), name));
    Query<UserDataSet> query = session.createQuery(criteria);
    return query.uniqueResult();
}
项目:dev-courses    文件:ToDoListDAO.java   
public List<ToDoList> rechercherToDoList() {

//Fonction hibernate pour construire les requêtes.
      final CriteriaBuilder lCriteriaBuilder = entityManager.getCriteriaBuilder();

      //Creation de la requête de select
      final CriteriaQuery<ToDoList> lCriteriaQuery = lCriteriaBuilder.createQuery(ToDoList.class);
      final Root<ToDoList> lRoot = lCriteriaQuery.from(ToDoList.class);
      lCriteriaQuery.select(lRoot);
      final TypedQuery<ToDoList> lTypedQuery = entityManager.createQuery(lCriteriaQuery);

      return lTypedQuery.getResultList();
  }
项目:osc-core    文件:SecurityGroupEntityMgr.java   
public static List<SecurityGroup> listByProtectAllAndProjectId(EntityManager em, String projectId) {
    CriteriaBuilder cb = em.getCriteriaBuilder();

    CriteriaQuery<SecurityGroup> query = cb.createQuery(SecurityGroup.class);

    Root<SecurityGroup> root = query.from(SecurityGroup.class);
    query = query.select(root)
            .distinct(true)
            .where(cb.and(
                    cb.equal(root.get("projectId"), projectId),
                    cb.equal(root.get("protectAll"), true)));

    return em.createQuery(query).getResultList();
}
项目:osc-core    文件:ApplianceManagerConnectorEntityMgr.java   
public static boolean isManagerTypeUsed(String managerType, EntityManager em) {

        try {
            CriteriaBuilder cb = em.getCriteriaBuilder();
            CriteriaQuery<Long> cq;
            Root<?> from;

            cq = cb.createQuery(Long.class);
            from = cq.from(ApplianceManagerConnector.class);
            cq = cq.select(cb.count(from))
                    .where(cb.equal(from.get("managerType"), managerType));

            Long count1 = em.createQuery(cq).getSingleResult();

            cq = cb.createQuery(Long.class);
            from = cq.from(Appliance.class);
            cq = cq.select(cb.count(from))
                    .where(cb.equal(from.get("managerType"), managerType));

            Long count2 = em.createQuery(cq).getSingleResult();

            return count1 > 0 || count2 > 0;
        } catch (Exception e) {
            return true;
        }

    }
项目:WordnetLoom    文件:ExtGraphRepository.java   
public Collection<ExtGraph> findByWordAndPackageNo(String word, int packageno) {

        Long pkg = new Long(packageno);
        CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
        CriteriaQuery<ExtGraph> criteriaQuery = criteriaBuilder.createQuery(ExtGraph.class
        );

        Root<ExtGraph> root = criteriaQuery.from(ExtGraph.class);
        Join<ExtGraph, Synset> synset = root.join("synset", JoinType.INNER);
        Join<Synset, Sense> sts = synset.join("sense", JoinType.LEFT);
        List<Predicate> criteriaList = new ArrayList<>();

        Predicate firstCondition = criteriaBuilder.equal(root.get("word"), word);
        criteriaList.add(firstCondition);

        Predicate secondCondition = criteriaBuilder.equal(root.get("packageno"), pkg);
        criteriaList.add(secondCondition);

        Predicate thirdCondition = criteriaBuilder.equal(sts.get("senseIndex"), 0);
        criteriaList.add(thirdCondition);

        criteriaQuery.where(criteriaBuilder.and(criteriaList.toArray(new Predicate[0])));
        final TypedQuery<ExtGraph> query = getEntityManager().createQuery(criteriaQuery);

        return query.getResultList();
    }
项目:flow-platform    文件:NodeResultDaoImpl.java   
@Override
public List<NodeResult> list(BigInteger jobId) {
    return execute(session -> {
        CriteriaBuilder builder = session.getCriteriaBuilder();
        CriteriaQuery<NodeResult> select = builder.createQuery(NodeResult.class);
        Root<NodeResult> nodeResultRoot = select.from(NodeResult.class);
        Predicate aCondition = builder.equal(nodeResultRoot.get("key").get("jobId"), jobId);
        select.where(aCondition);
        select.orderBy(builder.asc(nodeResultRoot.get("order")));
        return session.createQuery(select).list();
    });
}
项目:otus_java_2017_06    文件:UserDataSetDAO.java   
public UserDataSet readByName(String name) {
    CriteriaBuilder builder = session.getCriteriaBuilder();
    CriteriaQuery<UserDataSet> criteria = builder.createQuery(UserDataSet.class);
    Root<UserDataSet> from = criteria.from(UserDataSet.class);
    criteria.where(builder.equal(from.get("name"), name));
    Query<UserDataSet> query = session.createQuery(criteria);
    return query.uniqueResult();
}
项目:osc-core    文件:TaskEntityMgr.java   
public List<TaskRecord> getUncompletedTasks() {
    CriteriaBuilder cb = this.em.getCriteriaBuilder();

    CriteriaQuery<TaskRecord> query = cb.createQuery(TaskRecord.class);
    Root<TaskRecord> from = query.from(TaskRecord.class);

    query = query.select(from).where(
            cb.notEqual(from.get("state"), COMPLETED));

    return this.em.createQuery(query).getResultList();
}
项目:bootstrap    文件:PaginationDao.java   
/**
 * Creates a new count query for the given {@link Specification}.
 */
private <T> TypedQuery<Long> getCountQuery(final Class<T> entityType, final Specification<T> spec) {

    final CriteriaBuilder builder = em.getCriteriaBuilder();
    final CriteriaQuery<Long> query = builder.createQuery(Long.class);

    final Root<T> root = query.from(entityType);
    applySpecificationToCriteria(root, spec, query);
    query.select(builder.count(root));

    return em.createQuery(query);
}
项目:osc-core    文件:SecurityGroupEntityMgr.java   
public static List<SecurityGroup> listOtherSecurityGroupsWithSameSFC(EntityManager em, SecurityGroup sg) {
    CriteriaBuilder cb = em.getCriteriaBuilder();

    CriteriaQuery<SecurityGroup> query = cb.createQuery(SecurityGroup.class);

    Root<SecurityGroup> root = query.from(SecurityGroup.class);
    query = query.select(root).where(cb.equal(root.join("serviceFunctionChain"), sg.getServiceFunctionChain()),
            cb.equal(root.get("projectId"), sg.getProjectId()), cb.notEqual(root, sg),
            cb.isNotNull(root.get("networkElementId")));

    List<SecurityGroup> list = em.createQuery(query).getResultList();
    return list;
}
项目:owl    文件:BaseFilterSpecification.java   
protected static Predicate and(CriteriaBuilder criteriaBuilder, Predicate... predicate) {
    Predicate result = null;
    for (int i = 0; i < predicate.length; i++) {
        if (predicate[i] != null) {
            if (result == null) {
                result = predicate[i];
            } else {
                result = criteriaBuilder.and(result, predicate[i]);
            }
        }
    }

    return result;
}
项目:sctalk    文件:LogicalExpression.java   
@Override
public Predicate toPredicate(Root<?> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
    List<Predicate> predicates = new ArrayList<Predicate>();
    for (int i = 0; i < this.criterion.length; i++) {
        predicates.add(this.criterion[i].toPredicate(root, query, builder));
    }
    switch (operator) {
    case OR:
        return builder.or(predicates.toArray(new Predicate[predicates.size()]));
    default:
        return null;
    }
}