Java Code Examples for javax.persistence.criteria.CriteriaBuilder

The following are top voted examples for showing how to use javax.persistence.criteria.CriteriaBuilder. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: marathonv5   File: LiveSalesListFacadeREST.java   Source Code and License 17 votes vote down vote up
@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();
}
 
Example 2
Project: owl   File: TestSuiteFilterSpecification.java   Source Code and License 16 votes vote down vote up
@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;
}
 
Example 3
Project: plumdo-work   File: SimpleExpression.java   Source Code and License 16 votes vote down vote up
@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;  
    }  
}
 
Example 4
Project: WordnetLoom   File: ExtGraphRepository.java   Source Code and License 13 votes vote down vote up
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();
    }
 
Example 5
Project: spring-microservice-sample   File: PostSpecifications.java   Source Code and License 11 votes vote down vote up
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()]));
    };
}
 
Example 6
Project: otus_java_2017_10   File: ConnectionHelper.java   Source Code and License 8 votes vote down vote up
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);


}
 
Example 7
Project: photoiff   File: PerfilService.java   Source Code and License 8 votes vote down vote up
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;
}
 
Example 8
Project: amanda   File: AbstractJpaCriterionRepository.java   Source Code and License 7 votes vote down vote up
@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);
}
 
Example 9
Project: bootstrap   File: PaginationDao.java   Source Code and License 7 votes vote down vote up
/**
 * 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));
		}
	}
}
 
Example 10
Project: OperatieBRP   File: VerConvRepositoryImpl.java   Source Code and License 7 votes vote down vote up
@Override
public final Lo3Voorkomen zoekLo3VoorkomenVoorActie(final Long actieId) {
    final CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
    final CriteriaQuery<Lo3Voorkomen> criteria = criteriaBuilder.createQuery(Lo3Voorkomen.class);
    final Root<Lo3Voorkomen> criteriaRoot = criteria.from(Lo3Voorkomen.class);
    criteria.select(criteriaRoot);
    criteria.where(new Predicate[] {criteriaBuilder.equal(criteriaRoot.get("actie").get("id"), actieId) });

    final List<Lo3Voorkomen> result = em.createQuery(criteria).getResultList();
    return result.isEmpty() ? null : result.get(0);
}
 
Example 11
Project: chr-krenn-fhj-ws2017-sd17-pse   File: CommunityDAOImpl.java   Source Code and License 7 votes vote down vote up
@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;
	}
}
 
Example 12
Project: bibliometrics   File: RolePermissionDAO.java   Source Code and License 7 votes vote down vote up
/**
 * 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;
}
 
Example 13
Project: osc-core   File: PodEntityMgr.java   Source Code and License 6 votes vote down vote up
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;
        }
    }
 
Example 14
Project: datatable-java   File: DatatableDAOImpl.java   Source Code and License 6 votes vote down vote up
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;
  }
 
Example 15
Project: marathonv5   File: LiveSalesListFacadeREST.java   Source Code and License 6 votes vote down vote up
@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();
}
 
Example 16
Project: marathonv5   File: LiveSalesListFacadeREST.java   Source Code and License 6 votes vote down vote up
@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();
}
 
Example 17
Project: marathonv5   File: LiveSalesListFacadeREST.java   Source Code and License 6 votes vote down vote up
@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();
}
 
Example 18
Project: spring-repository-plus   File: SpecificationImpl.java   Source Code and License 6 votes vote down vote up
@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()]));
}
 
Example 19
Project: cr-private-server   File: ClanService.java   Source Code and License 6 votes vote down vote up
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();
	}
}
 
Example 20
Project: osc-core   File: ApplianceEntityMgr.java   Source Code and License 6 votes vote down vote up
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;
    }
}
 
Example 21
Project: sucok-framework   File: BetweenField.java   Source Code and License 6 votes vote down vote up
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public Predicate buildJpaPredicate(CriteriaBuilder cb, Root root) {
	String field1 = (String) Array.get(value, 0);
	String field2 = (String) Array.get(value, 1);
	Expression<Comparable> path1 = QueryFormHelper.getPath(root, field1);
	Expression<Comparable> path2 = QueryFormHelper.getPath(root, field2);
	Expression<Comparable> parameter = cb.literal((Comparable) value);
	return cb.between(parameter, path1, path2);
}
 
Example 22
Project: chr-krenn-fhj-ws2017-sd17-pse   File: CommunityDAOImpl.java   Source Code and License 6 votes vote down vote up
@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;
	}
}
 
Example 23
Project: osc-core   File: VirtualizationConnectorEntityMgr.java   Source Code and License 6 votes vote down vote up
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;
    }
 
Example 24
Project: spring-data-examples   File: CustomerSpecifications.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
		}
	};
}
 
Example 25
Project: security-mgr-sample-plugin   File: IsmPolicyApi.java   Source Code and License 6 votes vote down vote up
@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);
        }
    });
}
 
Example 26
Project: security-mgr-sample-plugin   File: IsmSecurityGroupApi.java   Source Code and License 6 votes vote down vote up
@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;
    });
}
 
Example 27
Project: esup-sgc   File: Card.java   Source Code and License 6 votes vote down vote up
private static Expression<Boolean> getFullTestSearchExpression(CriteriaBuilder cb, String searchString) {
    return cb.function("fts", Boolean.class, cb.literal(searchString));
}
 
Example 28
Project: aws-photosharing-example   File: UserFacade.java   Source Code and License 5 votes vote down vote up
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;
	}		
}
 
Example 29
Project: C4SG-Obsolete   File: UserSpecification.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 30
Project: cloud   File: ByRangeSpecification.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 31
Project: osc-core   File: SecurityGroupEntityMgr.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 32
Project: c4sg-services   File: UserSpecification.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 33
Project: otus_java_2017_06   File: UserDataSetDAO.java   Source Code and License 5 votes vote down vote up
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();
}
 
Example 34
Project: dev-courses   File: ToDoListDAO.java   Source Code and License 5 votes vote down vote up
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();
  }
 
Example 35
Project: osc-core   File: SecurityGroupEntityMgr.java   Source Code and License 5 votes vote down vote up
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();
}
 
Example 36
Project: osc-core   File: ApplianceManagerConnectorEntityMgr.java   Source Code and License 5 votes vote down vote up
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;
        }

    }
 
Example 37
Project: flow-platform   File: NodeResultDaoImpl.java   Source Code and License 5 votes vote down vote up
@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();
    });
}
 
Example 38
Project: otus_java_2017_06   File: UserDataSetDAO.java   Source Code and License 5 votes vote down vote up
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();
}
 
Example 39
Project: osc-core   File: TaskEntityMgr.java   Source Code and License 5 votes vote down vote up
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();
}
 
Example 40
Project: bootstrap   File: PaginationDao.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
}