Java Code Examples for javax.persistence.criteria.Root

The following are top voted examples for showing how to use javax.persistence.criteria.Root. 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: 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 2
Project: tap17-muggl-javaee   File: RequestBean.java   Source Code and License 15 votes vote down vote up
public List<PlayerDetails> getPlayersBySport(String sport) {
    logger.info("getPlayersByLeagueId");
    List<Player> players = null;

    try {
        CriteriaQuery<Player> cq = cb.createQuery(Player.class);
        if (cq != null) {
            Root<Player> player = cq.from(Player.class);
            Join<Player, Team> team = player.join(Player_.teams);
            Join<Team, League> league = team.join(Team_.league);

            // Get MetaModel from Root
            //EntityType<Player> Player_ = player.getModel();

            // set the where clause
            cq.where(cb.equal(league.get(League_.sport), sport));
            cq.select(player).distinct(true);
            TypedQuery<Player> q = em.createQuery(cq);
            players = q.getResultList();
        }
        return copyPlayersToDetails(players);
    } catch (Exception ex) {
        throw new EJBException(ex);
    }
}
 
Example 3
Project: spring-microservice-sample   File: UserSpecifications.java   Source Code and License 13 votes vote down vote up
public static Specification<User> byKeyword(String keyword, String role, String active){
    return (Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {

        List<Predicate> predicates = new ArrayList<>();

        if (StringUtils.hasText(keyword)) {
            predicates.add(
                cb.or(
                    cb.like(root.get(User_.email), "%" + keyword + "%"),
                    cb.like(root.get(User_.username), "%" + keyword + "%")
                ));
        }

        if (StringUtils.hasText(role) && !"ALL".equals(role)) {

            ListJoin<User, String> roleJoin = root.join(User_.roles);
            predicates.add(cb.equal(roleJoin, role));
        }
        if (StringUtils.hasText(active)) {
            predicates.add(cb.equal(root.get(User_.active), Boolean.valueOf(active)));
        }
        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    };
}
 
Example 4
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 5
Project: osc-core   File: DeploymentSpecEntityMgr.java   Source Code and License 9 votes vote down vote up
public static DeploymentSpec findDeploymentSpecByVirtualSystemProjectAndRegion(EntityManager em, VirtualSystem vs,
        String projectId, String region) {

    CriteriaBuilder cb = em.getCriteriaBuilder();

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

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

    query = query.select(root)
            .where(cb.equal(root.get("projectId"), projectId),
                    cb.equal(root.get("region"), region),
                    cb.equal(root.get("virtualSystem"), vs));

    try {
        return em.createQuery(query).getSingleResult();
    } catch (NoResultException nre) {
        return null;
    }
}
 
Example 6
Project: os   File: GenericRepositoryImpl.java   Source Code and License 8 votes vote down vote up
private <S> S aggregate(CriteriaBuilder builder, CriteriaQuery<S> query, Root<E> root, Specification<E> spec, List<Selection<?>> selectionList, LockModeType lockMode) {
	if (selectionList != null) {
		Predicate predicate = spec.toPredicate(root, query, builder);
		if (predicate != null) {
			query.where(predicate);
		}
		query.multiselect(selectionList);
		return (S) em.createQuery(query).setLockMode(lockMode).getSingleResult();
	}
	return null;
}
 
Example 7
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 8
Project: owl   File: TestRunFilterSpecification.java   Source Code and License 7 votes vote down vote up
@Override
public Predicate toPredicate(Root<TestRun> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
	Predicate result = null;

	if (!CollectionUtils.isEmpty(filter.getBuilds())) {
		result = criteriaBuilder.in(root.get(BUILD_PROPERTY)).value(filter.getBuilds());
	}

	if (!CollectionUtils.isEmpty(filter.getTestSuites())) {
		result = and(criteriaBuilder, result,
				criteriaBuilder.in(root.get("testSuite").get("id")).value(filter.getTestSuites()));
	}

	if (!CollectionUtils.isEmpty(filter.getGit())) {
		result = and(criteriaBuilder, result,
				criteriaBuilder.or(
						criteriaBuilder.in(root.get("gitHash")).value(filter.getGit()),
						criteriaBuilder.in(root.get("gitBranch")).value(filter.getGit())
				));
	}

	result = and(criteriaBuilder, result, criteriaBuilder.isNotNull(root.get("testSuite")));

	return result;
}
 
Example 9
Project: OperatieBRP   File: CustomSimpleJpaRepository.java   Source Code and License 7 votes vote down vote up
/**
 * Spec op query doen.
 * @param spec spec
 * @param query query
 * @param <S> query type
 * @return root
 */
protected final <S> Root<T> applySpecificationToQueryCriteria(final Specification<T> spec, final CriteriaQuery<S> query) {

    Assert.notNull(query, "Query mag niet null zijn.");
    final Root<T> root = query.from(getDomainClass());

    if (spec == null) {
        return root;
    }

    final CriteriaBuilder builder = em.getCriteriaBuilder();
    final Predicate predicate = spec.toPredicate(root, query, builder);

    if (predicate != null) {
        query.where(predicate);
    }

    return root;
}
 
Example 10
Project: sucok-framework   File: QueryFormHelper.java   Source Code and License 7 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T, N extends Number> Expression<N> getExpression(CriteriaBuilder cb, Root<T> root, String input) {
	StringTokenizer tokenizer = new StringTokenizer(input, "+-*/", true);
	Expression<N> expr = getPath(root, tokenizer.nextToken());
	if (tokenizer.hasMoreTokens()) {
		String op = tokenizer.nextToken();
		String name = tokenizer.nextToken();
		Expression<N> expr2 = getPath(root, name);
		if ("+".equals(op)) {
			expr = cb.sum(expr, expr2);
		} else if ("-".equals(op)) {
			expr = cb.diff(expr, expr2);
		} else if ("*".equals(op)) {
			expr = cb.prod(expr, expr2);
		} else if ("/".equals(op)) {
			expr = (Expression<N>) cb.quot(expr, expr2);
		}
	}
	return expr;
}
 
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: datatable-java   File: DatatableSpecification.java   Source Code and License 6 votes vote down vote up
private Predicate getPredicateGlobalSearch(final Root<T> root, final CriteriaQuery<?> query, final CriteriaBuilder cb,
    Predicate predicate) {
    // check whether a global filter value exists
    final String globalFilterValue = input.getSearch().getValue();
    if (globalFilterValue != null && globalFilterValue.trim().length() > 0) {
        LOGGER.fine("filtre global: {"+ globalFilterValue+"}");

        Predicate matchOneColumnPredicate = cb.disjunction();
        // add a 'WHERE .. LIKE' clause on each searchable column
        for (final DatatableColumn column : input.getColumns()) {
            if (column.getSearchable()) {
                LOGGER.log(Level.FINE, "filtre global pour colonne: {}", column);
                final Expression<String> expression = DatatableHelper.getExpression(root, column.getData(), String.class);

                matchOneColumnPredicate = cb.or(matchOneColumnPredicate,
                    cb.like(cb.lower(expression), getLikeFilterValue(globalFilterValue), ESCAPE_CHAR));
            }
        }
        predicate = cb.and(predicate, matchOneColumnPredicate);
    }
    return predicate;
}
 
Example 13
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}/{orderLineId}")
public List<LiveSalesList> findRecentRegionProductTypeFrom(@PathParam("regionName") String regionName, @PathParam("productTypeId") 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.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 14
Project: cf-mta-deploy-service   File: ContextExtensionDao.java   Source Code and License 6 votes vote down vote up
private TypedQuery<ContextExtension> createQuery(String processId, String name, EntityManager manager) {
    CriteriaBuilder builder = manager.getCriteriaBuilder();
    CriteriaQuery<ContextExtension> query = builder.createQuery(ContextExtension.class);
    Root<ContextExtension> root = query.from(ContextExtension.class);

    List<Predicate> predicates = new ArrayList<>();
    if (processId != null) {
        predicates.add(builder.equal(root.get(ContextExtension.FieldNames.PROCESS_ID),
            builder.parameter(String.class, ContextExtension.FieldNames.PROCESS_ID)));
    }
    if (name != null) {
        predicates.add(builder.equal(root.get(ContextExtension.FieldNames.NAME),
            builder.parameter(String.class, ContextExtension.FieldNames.NAME)));
    }

    return manager.createQuery(query.select(root).where(predicates.toArray(new Predicate[0])));

}
 
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: bibliometrics   File: UserDAO.java   Source Code and License 6 votes vote down vote up
public static User getUser(String username) {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("userData");
    EntityManager em = emf.createEntityManager();
	EntityTransaction tx = em.getTransaction();
	tx.begin();
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<User> q = cb.createQuery(User.class);
	Root<User> c = q.from(User.class);
	q.select(c).where(cb.equal(c.get("username"), username));
	TypedQuery<User> query = em.createQuery(q);
	List<User> users = query.getResultList();
	em.close();
	LOGGER.info("found " + users.size() + " users with username " + username);
	if (users.size() == 1)
		return users.get(0);
	else
		return null;
}
 
Example 17
Project: Pedidex   File: JpaCriteriaHelper.java   Source Code and License 6 votes vote down vote up
/**
 * Obtem lista com os resultados
 * @return Lista de resultados
 */
public List<T> getResults() {
    CriteriaQuery<T> criteriaQuery = criteriaBuilder.createQuery(entityClass);
    Root<T> root                   = criteriaQuery.from(entityClass);
    setupQuery(criteriaQuery, root);

    // ORDER BY
    if ( ! orders.isEmpty() ) {
        ArrayList<Order> jpaOrders = new ArrayList<>();
        for (OrderEntry orderField : orders) {
            if ( orderField.order.equals(OrderDirection.ASC) ) {
                jpaOrders.add( criteriaBuilder.asc(getPath(orderField.fieldNames, root)));
            } else {
                jpaOrders.add( criteriaBuilder.desc(getPath(orderField.fieldNames, root)));
            }
        }
        criteriaQuery.orderBy( jpaOrders );
    }

    if ( pageNumber != null ) {
        return em.createQuery(criteriaQuery).setFirstResult( (pageNumber - 1) * pageSize ).setMaxResults(pageSize)
                        .getResultList();
    } else {
        return em.createQuery(criteriaQuery).getResultList();
    }
}
 
Example 18
Project: minijax   File: DefaultBaseDao.java   Source Code and License 6 votes vote down vote up
/**
 * Returns a page of objects.
 *
 * @param entityClass The entity class.
 * @param page The page index (zero indexed).
 * @param pageSize The page size.
 * @return A page of objects.
 */
@Override
public <T extends BaseEntity> List<T> readPage(
        final Class<T> entityClass,
        final int page,
        final int pageSize) {

    final CriteriaBuilder cb = em.getCriteriaBuilder();
    final CriteriaQuery<T> cq = cb.createQuery(entityClass);
    final Root<T> root = cq.from(entityClass);
    cq.select(root);
    cq.orderBy(cb.desc(root.get("id")));
    return em.createQuery(cq)
            .setFirstResult(page * pageSize)
            .setMaxResults(pageSize)
            .getResultList();
}
 
Example 19
Project: tap17-muggl-javaee   File: RequestBean.java   Source Code and License 6 votes vote down vote up
public List<PlayerDetails> getPlayersByPosition(String position) {
    logger.info("getPlayersByPosition");
    List<Player> players = null;

    try {
        CriteriaQuery<Player> cq = cb.createQuery(Player.class);
        if (cq != null) {
            Root<Player> player = cq.from(Player.class);

            // Get MetaModel from Root
            //EntityType<Player> Player_ = player.getModel();

            // set the where clause
            cq.where(cb.equal(player.get(Player_.position), position));
            cq.select(player);
            TypedQuery<Player> q = em.createQuery(cq);
            players = q.getResultList();
        }
        return copyPlayersToDetails(players);
    } catch (Exception ex) {
        throw new EJBException(ex);
    }
}
 
Example 20
Project: tap17-muggl-javaee   File: RequestBean.java   Source Code and License 6 votes vote down vote up
public List<PlayerDetails> getPlayersNotOnTeam() {
    logger.info("getPlayersNotOnTeam");
    List<Player> players = null;

    try {
        CriteriaQuery<Player> cq = cb.createQuery(Player.class);
        if (cq != null) {
            Root<Player> player = cq.from(Player.class);

            // Get MetaModel from Root
            //EntityType<Player> Player_ = player.getModel();

            // set the where clause
            cq.where(cb.isEmpty(player.get(Player_.teams)));
            cq.select(player).distinct(true);
            TypedQuery<Player> q = em.createQuery(cq);
            players = q.getResultList();
        }
        return copyPlayersToDetails(players);
    } catch (Exception ex) {
        throw new EJBException(ex);
    }
}
 
Example 21
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 22
Project: sctalk   File: SimpleExpression.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public Predicate toPredicate(Root<?> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
    Path expression = null;
    if (fieldName.contains(".")) {
        
        System.out.println(root);
        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 RLIKE:
        return builder.like((Expression<String>) expression, value + "%");
    case LLIKE:
        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);
    case ISNULL:
        return builder.isNull(expression);
    case NOTNULL:
        return builder.isNotNull(expression);
    default:
        return null;
    }
}
 
Example 23
Project: security-mgr-sample-plugin   File: IsmDeviceApi.java   Source Code and License 6 votes vote down vote up
private DeviceMemberEntity getDeviceMember(Long deviceId, Long memberId, String memName) {
    CriteriaBuilder criteriaBuilder = IsmDeviceApi.this.em.getCriteriaBuilder();
    CriteriaQuery<DeviceMemberEntity> query = criteriaBuilder.createQuery(DeviceMemberEntity.class);
    Root<DeviceMemberEntity> r = query.from(DeviceMemberEntity.class);

    if (memName != null) {
        query.select(r)
        .where(criteriaBuilder.and((criteriaBuilder.equal(r.get("device").get("id"), deviceId)),
                (criteriaBuilder.equal(r.get("name"), memName))));
    } else {
        query.select(r).where(criteriaBuilder.and((criteriaBuilder.equal(r.get("device").get("id"), deviceId)),
                criteriaBuilder.equal(r.get("id"), memberId)));
    }

    List<DeviceMemberEntity> result = IsmDeviceApi.this.em.createQuery(query).getResultList();

    return result.isEmpty() == true ? null : result.get(0);
}
 
Example 24
Project: security-mgr-sample-plugin   File: IsmSecurityGroupApi.java   Source Code and License 6 votes vote down vote up
private SecurityGroupEntity findSecurityGroupByName(final String name, DeviceEntity device) throws Exception {

        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("name"), name), 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 name %s under device %s", name, device.getId()));
            }
            return result;
        });
    }
 
Example 25
Project: security-mgr-sample-plugin   File: IsmSecurityGroupInterfaceApi.java   Source Code and License 6 votes vote down vote up
private SecurityGroupInterfaceEntity getSecurityGroupInterfaceById(String id, DeviceEntity device)
        throws Exception {
    return this.txControl.supports(() -> {
        CriteriaBuilder cb = IsmSecurityGroupInterfaceApi.this.em.getCriteriaBuilder();
        CriteriaQuery<SecurityGroupInterfaceEntity> query = cb.createQuery(SecurityGroupInterfaceEntity.class);
        Root<SecurityGroupInterfaceEntity> root = query.from(SecurityGroupInterfaceEntity.class);

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

        SecurityGroupInterfaceEntity result = null;
        try {
            result = IsmSecurityGroupInterfaceApi.this.em.createQuery(query).getSingleResult();
        } catch (NoResultException e) {
            LOG.error(String.format("Cannot find Security group interface with id %s under device %s", id,
                    device.getId()));
        }
        return result;
    });
}
 
Example 26
Project: tap17-muggl-javaee   File: RequestBean.java   Source Code and License 6 votes vote down vote up
@GET
@Path("email/{guardianEmail}")
@Produces({"application/xml", "application/json"})
@RolesAllowed({"Guardian", "Administrator"})
public List<Student> getStatusByGuardianEmail(@PathParam("guardianEmail") String email) {
    logger.log(Level.INFO, "Principal is: {0}", ctx.getCallerPrincipal().getName());
    CriteriaQuery<Student> cq = cb.createQuery(Student.class);
    Root<Student> student = cq.from(Student.class);
    Join<Student, Guardian> guardian = student.join(Student_.guardians);

    cq.select(student);
    cq.where(cb.equal(guardian.get(Guardian_.email), email));
    cq.distinct(true);

    TypedQuery<Student> q = em.createQuery(cq);
    List<Student> results = q.getResultList();
    logger.log(Level.INFO, "Guardian {0}has {1} students.", new Object[]{email, results.size()});
    return results;
}
 
Example 27
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 28
Project: C4SG-Obsolete   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 29
Project: JAX-RS-JPA-CRUD   File: RepositoryCRUD.java   Source Code and License 5 votes vote down vote up
public default long count() {
    EntityManager entityManager = getEntityManager();
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();

    CriteriaQuery criteriaQuery = criteriaBuilder.createQuery();
    Root<E> root = criteriaQuery.from(getEntityClass());
    criteriaQuery.select(criteriaBuilder.count(root));
    TypedQuery<Long> query = entityManager.createQuery(criteriaQuery);

    return query.getSingleResult();
}
 
Example 30
Project: tap17-muggl-javaee   File: AdminBean.java   Source Code and License 5 votes vote down vote up
public List<Address> getAllAddresses() {
    CriteriaQuery<Address> cq = em.getCriteriaBuilder().createQuery(Address.class);
    Root<Address> address = cq.from(Address.class);
    cq.select(address);
    cq.where(cb.isTrue(address.get(Address_.active)));
    cq.distinct(true);
    TypedQuery<Address> q = em.createQuery(cq);
    return q.getResultList();
}
 
Example 31
Project: REST-Web-Services   File: ContributionSpecs.java   Source Code and License 5 votes vote down vote up
/**
 * Generate a criteria query predicate for a where clause based on the given parameters.
 *
 * @param root The root to use
 * @param cb The criteria builder to use
 * @param movie The MovieEntity object
 * @param field The movie field
 * @param status The contribution status
 * @param fromDate Creation date range "from"
 * @param toDate Creation date range "to"
 * @return The specification
 */
public static Predicate getFindPredicate(
        final Root<ContributionEntity> root,
        final CriteriaBuilder cb,
        @Nullable final MovieEntity movie,
        @Nullable final MovieField field,
        @Nullable final DataStatus status,
        @Nullable final Date fromDate,
        @Nullable final Date toDate
) {
    final List<Predicate> predicates = new ArrayList<>();

    if (Optional.ofNullable(movie).isPresent()) {
        predicates.add(cb.equal(root.get(ContributionEntity_.movie), movie));
    }
    if (Optional.ofNullable(field).isPresent()) {
        predicates.add(cb.equal(root.get(ContributionEntity_.field), field));
    }
    if (Optional.ofNullable(status).isPresent()) {
        predicates.add(cb.equal(root.get(ContributionEntity_.status), status));
    }
    if (fromDate != null) {
        predicates.add(cb.greaterThanOrEqualTo(root.get(ContributionEntity_.created), fromDate));
    }
    if (toDate != null) {
        predicates.add(cb.lessThanOrEqualTo(root.get(ContributionEntity_.created), toDate));
    }

    return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}
 
Example 32
Project: datatable-java   File: DatatableSpecification.java   Source Code and License 5 votes vote down vote up
private Predicate getPredicateColonnes(final Root<T> root, final CriteriaQuery<?> query, final CriteriaBuilder cb,
    Predicate predicate) {
    // check for each searchable column whether a filter value exists
    for (final DatatableColumn column : input.getColumns()) {
        final boolean isColumnSearchable =
            column.getSearchable() && column.getSearch() != null
                && hasText(column.getSearch().getValue());
        if (!isColumnSearchable) {
            continue;
        }

        LOGGER.fine("colonne a filtrer: {"+ column+"}");

        // the filter contains only one value, add a 'WHERE .. LIKE'
        // clause
        if (isBoolean(column.getSearch().getValue())) {
            final Expression<Boolean> booleanExpression = DatatableHelper.getExpression(root, column.getData(), Boolean.class);
            predicate =
                cb.and(predicate, cb.equal(booleanExpression, Boolean.valueOf(column.getSearch().getValue())));
        } else {
            final Expression<String> stringExpression = DatatableHelper.getExpression(root, column.getData(), String.class);
            predicate = cb.and(predicate, cb.like(cb.lower(stringExpression),
                getLikeFilterValue(column.getSearch().getValue()), ESCAPE_CHAR));
        }

    }
    return predicate;
}
 
Example 33
Project: Info-Portal   File: AbstractRepository.java   Source Code and License 5 votes vote down vote up
protected List<T> findAll(Class<T> clazz) {
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    CriteriaQuery<T> cq = cb.createQuery(clazz);
    Root<T> rootEntry = cq.from(clazz);
    CriteriaQuery<T> all = cq.select(rootEntry);
    TypedQuery<T> allQuery = getEntityManager().createQuery(all);
    return allQuery.getResultList();
}
 
Example 34
Project: tap17-muggl-javaee   File: RequestBean.java   Source Code and License 5 votes vote down vote up
public List<StatusEntry> getStatusEntriesByDate(Date date) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    CriteriaQuery<StatusEntry> cq = cb.createQuery(StatusEntry.class);
    Root<StatusEntry> statusEntry = cq.from(StatusEntry.class);

    cq.select(statusEntry);
    cq.where(cb.equal(statusEntry.get(StatusEntry_.statusDate), cal));
    cq.distinct(true);

    TypedQuery<StatusEntry> q = em.createQuery(cq);
    return q.getResultList();
}
 
Example 35
Project: marathonv5   File: LiveSalesListFacadeREST.java   Source Code and License 5 votes vote down vote up
@GET
@Produces({"application/xml", "application/json"})
@Path("/recent/producttype/{id}")
public List<LiveSalesList> findRecentProductType(@PathParam("id") 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.equal(liveSalesList.get(LiveSalesList_.productTypeId), productTypeId));
    Query q = getEntityManager().createQuery(cq);
    q.setMaxResults(500);
    return q.getResultList();
}
 
Example 36
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 37
Project: xsharing-services-router   File: ComputationLogRepositoryImpl.java   Source Code and License 5 votes vote down vote up
@Override
public ComputationLog findLog(DateTime timestamp) throws DatabaseException {
    // find log by time stamp
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<ComputationLog> c = cb.createQuery(ComputationLog.class);
    Root<ComputationLog> log = c.from(ComputationLog.class);
    c.where(cb.equal(log.get(ComputationLog_.timestamp), timestamp));
    TypedQuery<ComputationLog> query = entityManager.createQuery(c);

    try {
        return query.getSingleResult();
    } catch (RuntimeException e) {
        throw new DatabaseException(e.getMessage());
    }
}
 
Example 38
Project: careconnect-reference-implementation   File: ValueSetDao.java   Source Code and License 5 votes vote down vote up
private ValueSetEntity findValueSetEntity(IdType theId) {

        ValueSetEntity valueSetEntity = null;
        // Only look up if the id is numeric else need to do a search
        if (daoutils.isNumeric(theId.getValue())) {
            valueSetEntity =(ValueSetEntity) em.find(ValueSetEntity.class, theId.getValue());
        }

        // if null try a search on strId
        if (valueSetEntity == null)
        {
            CriteriaBuilder builder = em.getCriteriaBuilder();

            CriteriaQuery<ValueSetEntity> criteria = builder.createQuery(ValueSetEntity.class);
            Root<ValueSetEntity> root = criteria.from(ValueSetEntity.class);
            List<Predicate> predList = new LinkedList<Predicate>();
            Predicate p = builder.equal(root.<String>get("strId"),theId.getValue());
            predList.add(p);
            Predicate[] predArray = new Predicate[predList.size()];
            predList.toArray(predArray);
            if (predList.size()>0)
            {
                criteria.select(root).where(predArray);

                List<ValueSetEntity> qryResults = em.createQuery(criteria).getResultList();

                for (ValueSetEntity cme : qryResults)
                {
                    valueSetEntity = cme;
                    break;
                }
            }
        }
        return valueSetEntity;
    }
 
Example 39
Project: datatable-java   File: DatatableHelper.java   Source Code and License 5 votes vote down vote up
/**
 * Cree une expression Criteria API avec l'atribut de l'entité passé en parametre
 * 
 * @param root
 *            entité JPA contenant le champ
 * @param columnData
 *            nom du champ
 * @param clazz
 *            class du champ
 * @param <S>
 *            type du champ
 * @return l'expression de l'atribut
 */
public static <S> Path<S> getExpression(final Root<?> root, final String columnData, final Class<S> clazz) {
    if (!columnData.contains(DatatableSpecification.ATTRIBUTE_SEPARATOR)) {
        // columnData is like "attribute" so nothing particular to do
        return root.get(columnData);
    }
    // columnData is like "joinedEntity.attribute" so add a join clause
    final String[] values = columnData.split(DatatableSpecification.ESCAPED_ATTRIBUTE_SEPARATOR);
    final Attribute<?, ?> attribute = root.getModel().getAttribute(values[0]);
    if (attribute == null) {
        throw new IllegalArgumentException(
            "Colonne '" + values[0] + "' (" + columnData + ") introuvable depuis l'entité '" + root.getJavaType()
                + "'");
    }
    if (attribute.getPersistentAttributeType() == PersistentAttributeType.EMBEDDED) {
        // with @Embedded attribute
        return root.get(values[0]).get(values[1]);
    }
    From<?, ?> from = root;
    for (int i = 0; i < values.length - 1; i++) {

        Join<?, ?> join = null;
        for (final Join<?, ?> joinCandidate : from.getJoins()) {
            if (joinCandidate.getAttribute().getName().equals(values[i])) {
                // LOGGER.debug("Trouve joint d'entite: '{}'", values[i]);
                join = joinCandidate;
            }
        }
        if (join == null) {
            // LOGGER.debug("Joigant entite '{}'...", values[i]);
            join = from.join(values[i], JoinType.INNER);
        }
        from = join;
    }
    return from.get(values[values.length - 1]);
}
 
Example 40
Project: OperatieBRP   File: AdministratieveHandelingFilterFactory.java   Source Code and License 5 votes vote down vote up
@Override
public Predicate toPredicate(final Root<?> administratieveHandelingRoot, final CriteriaQuery<?> query, final CriteriaBuilder cb) {
    final Root<PersoonAfgeleidAdministratiefHistorie> persoonHistoryRoot = query.from(PersoonAfgeleidAdministratiefHistorie.class);

    // Join persoon
    final Predicate joinPredicate = administratieveHandelingRoot.get(ID).in(persoonHistoryRoot.get(ADMINISTRATIEVE_HANDELING).get(ID));

    // Bsn
    final Predicate bsnPredicate = cb.equal(persoonHistoryRoot.get(PERSOON).get(BURGERSERVICE_NUMMER), value);

    return cb.and(bsnPredicate, joinPredicate);
}
 
Example 41
Project: Pedidex   File: JpaCriteriaHelper.java   Source Code and License 5 votes vote down vote up
/**
 * Efetua a contagem dos registros da consulta
 * @return numero de registros retornados pela consulta
 */
public long count() {
    CriteriaQuery<Long> criteriaQuery = criteriaBuilder.createQuery(Long.class);
    Root<T>                 rootCount = criteriaQuery.from(entityClass);

    criteriaQuery.select( criteriaBuilder.count( rootCount ) );

    if ( ! wheres.isEmpty() ) {
        criteriaQuery.where( getPredicates(rootCount, wheres) );
    }

    return em.createQuery( criteriaQuery ).getSingleResult();
}
 
Example 42
Project: osc-core   File: SecurityGroupEntityMgr.java   Source Code and License 5 votes vote down vote up
public static List<SecurityGroup> listSecurityGroupsByVcId(EntityManager em, Long vcId) {
    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.equal(root.join("virtualizationConnector").get("id"), vcId))
            .orderBy(cb.asc(root.get("name")));

    return em.createQuery(query).getResultList();
}
 
Example 43
Project: tap17-muggl-javaee   File: RequestBean.java   Source Code and License 5 votes vote down vote up
public List<PlayerDetails> getPlayersBySalaryRange(int low, int high) {
    logger.info("getPlayersBySalaryRange");
    List<Player> players = null;

    try {
        CriteriaQuery<Player> cq = cb.createQuery(Player.class);
        if (cq != null) {
            Root<Player> player = cq.from(Player.class);

            // Get MetaModel from Root
            //EntityType<Player> Player_ = player.getModel();

            // set the where clause
            cq.where(cb.between(player.get(
                    Player_.salary),
                    (double)low,
                    (double)high));
            // set the select clause
            cq.select(player).distinct(true);
            TypedQuery<Player> q = em.createQuery(cq);
            players = q.getResultList();
        }
        return copyPlayersToDetails(players);
    } catch (Exception ex) {
        throw new EJBException(ex);
    }
}
 
Example 44
Project: osc-core   File: OSCEntityManager.java   Source Code and License 5 votes vote down vote up
public List<T> listByFieldName(String entityClassFieldName, Object fieldValue) {
    CriteriaBuilder cb = this.em.getCriteriaBuilder();

    CriteriaQuery<T> query = cb.createQuery(this.clazz);

    Root<T> root = query.from(this.clazz);
    query = query.select(root)
            .distinct(true)
            .where(
                    cb.equal(root.get(entityClassFieldName), fieldValue));

    List<T> list = this.em.createQuery(query).getResultList();

    return list;
}
 
Example 45
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 46
Project: tasfe-framework   File: BaseRepositoryImpl.java   Source Code and License 5 votes vote down vote up
@Override
public T findOneByField(String Field, Object value) {
	CriteriaBuilder cb = entityManager.getCriteriaBuilder();
	CriteriaQuery<T> query = cb.createQuery(getDomainClass());
	Root<T> e = query.from(getDomainClass());
	query.where(cb.equal(e.get(Field), value));
	return entityManager.createQuery(query).getSingleResult();
}
 
Example 47
Project: sctalk   File: SearchCriteria.java   Source Code and License 5 votes vote down vote up
@Override
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
    if (!criterions.isEmpty()) {
        List<Predicate> predicates = new ArrayList<Predicate>();
        for (Criterion c : criterions) {
            predicates.add(c.toPredicate(root, query, builder));
        }
        // 将所有条件用 and 联合起来
        if (predicates.size() > 0) {
            return builder.and(predicates.toArray(new Predicate[predicates.size()]));
        }
    }
    return builder.conjunction();
}
 
Example 48
Project: sucok-framework   File: QueryFormHelper.java   Source Code and License 5 votes vote down vote up
public static <X, T> Expression<X> getPath(Root<T> root, String name) {
	String[] array = name.split("[.]");
	Expression<X> expr = root.get(array[0]);
	for (int i = 1; i < array.length; i++) {
		expr = ((Path<X>) expr).get(array[i]);
	}
	return expr;
}
 
Example 49
Project: OperatieBRP   File: PersoonFilterFactory.java   Source Code and License 5 votes vote down vote up
@Override
public Predicate toPredicate(final Root<?> persoonRoot, final CriteriaQuery<?> query, final CriteriaBuilder cb) {
    final Root<PersoonAdres> persoonAdressenRoot = query.from(PersoonAdres.class);
    final Predicate joinPredicateAdressen = persoonRoot.get(ID).in(persoonAdressenRoot.get(PERSOON).get(ID));

    final Expression<String> attributeExpression1 =
            cb.lower(cb.function(UNACCENT, String.class, persoonAdressenRoot.get("buitenlandsAdresRegel1")));
    final Expression<String> attributeExpression2 =
            cb.lower(cb.function(UNACCENT, String.class, persoonAdressenRoot.get("buitenlandsAdresRegel2")));
    final Expression<String> attributeExpression3 =
            cb.lower(cb.function(UNACCENT, String.class, persoonAdressenRoot.get("buitenlandsAdresRegel3")));
    final Expression<String> attributeExpression4 =
            cb.lower(cb.function(UNACCENT, String.class, persoonAdressenRoot.get("buitenlandsAdresRegel4")));
    final Expression<String> attributeExpression5 =
            cb.lower(cb.function(UNACCENT, String.class, persoonAdressenRoot.get("buitenlandsAdresRegel5")));
    final Expression<String> attributeExpression6 =
            cb.lower(cb.function(UNACCENT, String.class, persoonAdressenRoot.get("buitenlandsAdresRegel6")));
    final Expression<String> valueExpression =
            cb.lower(
                    cb.function(
                            UNACCENT,
                            String.class,
                            cb.concat(cb.concat(cb.literal(WILDCARD), cb.literal(value.toString())), cb.literal(WILDCARD))));
    final Predicate adresPredicate1 = cb.like(attributeExpression1, valueExpression);
    final Predicate adresPredicate2 = cb.like(attributeExpression2, valueExpression);
    final Predicate adresPredicate3 = cb.like(attributeExpression3, valueExpression);
    final Predicate adresPredicate4 = cb.like(attributeExpression4, valueExpression);
    final Predicate adresPredicate5 = cb.like(attributeExpression5, valueExpression);
    final Predicate adresPredicate6 = cb.like(attributeExpression6, valueExpression);

    final Predicate buitenlandsAdres = cb.or(adresPredicate1, adresPredicate2, adresPredicate3, adresPredicate4, adresPredicate5, adresPredicate6);
    return cb.and(joinPredicateAdressen, buitenlandsAdres);
}
 
Example 50
Project: cf-mta-deploy-service   File: DeployTargetDao.java   Source Code and License 5 votes vote down vote up
private TypedQuery<Dto> createFindByNameQuery(String name) {
    EntityManager em = createEntityManager();
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Dto> query = builder.createQuery(this.classVersion);
    Root<Dto> entity = query.from(this.classVersion);

    Predicate namePredicate = builder.equal(entity.get(DEPLOY_TARGET_NAME), name);
    return em.createQuery(query.select(entity).where(namePredicate));
}
 
Example 51
Project: chr-krenn-fhj-ws2017-sd17-pse   File: UserDAOImpl.java   Source Code and License 5 votes vote down vote up
@Override
public User findByUsername(String username) {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<User> criteria = builder.createQuery(User.class);
    Root<User> user = criteria.from(User.class);
    criteria.where(builder.equal(user.get("username"), username));
    TypedQuery<User> query = em.createQuery(criteria);
    try {
        User u = query.getSingleResult();
        return initializeUser(u);
    } catch (NoResultException e) {
        return null;
    }
}
 
Example 52
Project: aws-photosharing-example   File: ServiceFacade.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> Predicate getFilterPredicate(Function<Predicate[], Predicate>  p_method, Root<T> p_root, CriteriaBuilder p_builder, Filter[] p_filter) {
	 
	 Predicate predicate = null;
	 
	 if (p_filter != null && p_filter.length > 0) {	
			Path<?> property_path = null;							
			LinkedList<Predicate> predicates = new LinkedList<Predicate>();				
			
			for (Filter filter: p_filter) {							
				for (String hop : filter.getPropertyPath()) {
					if (property_path == null)
						property_path = p_root.get(hop);
					else
						property_path = property_path.get(hop);
				}
				if (filter.getValue() != null) {
					if (filter.isExact())
						predicates.add(p_builder.equal(property_path, filter.getValue()));
					else
						predicates.add(p_builder.like((Expression<String>) property_path, filter.getValue()+"%"));
				} else {
					if (filter.isInverse())
						predicates.add(p_builder.isNotNull(property_path));
					else
						predicates.add(p_builder.isNull(property_path));
				}
				
				property_path = null;					
			}											
			
			if (predicates.size() > 1)
				predicate = p_method.apply(predicates.toArray(new Predicate[predicates.size()]));
			else
				predicate = predicates.get(0);							
	}				 
	return predicate;
 }
 
Example 53
Project: sucok-framework   File: LessThanOrEqual.java   Source Code and License 5 votes vote down vote up
@Override
@SuppressWarnings({ "unchecked" })
public Predicate buildJpaPredicate(CriteriaBuilder cb, Root<?> root) {
	Expression<Y> path = QueryFormHelper.getPath(root, field);
	Y num = (Y) value;
	return cb.lessThanOrEqualTo(path, num);
}
 
Example 54
Project: OperatieBRP   File: OrPredicateBuilder.java   Source Code and License 5 votes vote down vote up
@Override
public Predicate toPredicate(final Root<?> root, final CriteriaQuery<?> query, final CriteriaBuilder cb) {
    final List<Predicate> predicates = new ArrayList<>();

    for (final PredicateBuilder predicateBuilder : predicateBuilders) {
        final Predicate predicate = predicateBuilder.toPredicate(root, query, cb);
        if (predicate != null) {
            predicates.add(predicate);
        }
    }

    return cb.or(predicates.toArray(new Predicate[] {}));
}
 
Example 55
Project: Planchester   File: PersistanceFacade.java   Source Code and License 5 votes vote down vote up
public T get(Predicate<T> predicate) {
    Session session = DatabaseConnectionHandler.getInstance().beginTransaction();

    CriteriaBuilder builder = session.getCriteriaBuilder();
    CriteriaQuery<T> query = builder.createQuery(persistanceClass);
    Root<T> root = query.from(persistanceClass);
    query.select(root);

    List<T> list;
    if (predicate == null) {
        list = session.createQuery(query).list();
    } else {
        list = session.createQuery(query).stream().filter(predicate).collect(Collectors.toList());
    }

    T object;
    if(list.isEmpty()) {
        object = null;
    } else {
        object = list.get(0);
    }

    DatabaseConnectionHandler.getInstance().commitTransaction();
    return object;
}
 
Example 56
Project: Pedidex   File: JpaCriteriaHelper.java   Source Code and License 5 votes vote down vote up
/**
 * Obtem unico registro do resultado da consulta
 * @return O primeiro objeto retornado da consulta
 */
public T getSingleResult() {
    CriteriaQuery<T> criteriaQuery = criteriaBuilder.createQuery(entityClass);
    Root<T> root                   = criteriaQuery.from(entityClass);
    setupQuery(criteriaQuery, root);

    return em.createQuery(criteriaQuery).getSingleResult();
}
 
Example 57
Project: tap17-muggl-javaee   File: RequestBean.java   Source Code and License 5 votes vote down vote up
public List<PlayerDetails> getPlayersByCity(String city) {
    logger.info("getPlayersByCity");
    List<Player> players = null;

    try {
        CriteriaQuery<Player> cq = cb.createQuery(Player.class);
        if (cq != null) {
            Root<Player> player = cq.from(Player.class);
            Join<Player, Team> team = player.join(Player_.teams);

            // Get MetaModel from Root
            //EntityType<Player> Player_ = player.getModel();

            // set the where clause
            cq.where(cb.equal(team.get(Team_.city), city));
            cq.select(player).distinct(true);
            TypedQuery<Player> q = em.createQuery(cq);
            players = q.getResultList();
        }
        return copyPlayersToDetails(players);
    } catch (Exception ex) {
        throw new EJBException(ex);
    }
}
 
Example 58
Project: datatable-java   File: DatatableOrSpecification.java   Source Code and License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Predicate toPredicate(final Root<T> root, final CriteriaQuery<?> query, final CriteriaBuilder cb) {

	LOGGER.log(Level.FINE, "Creating OR search predicate: '{}':'{}'", new Object[]{search, colonnes});

    // liste de predicats pour aprés faire le "or"
    final List<Predicate> predicates = new ArrayList<Predicate>();

    // valeur a chercher
    final String valeurRecherche = search.getValue().trim().toLowerCase();

    for (final DatatableColumn colonne : colonnes) {
        final Path<?> expression = DatatableHelper.getExpression(root, colonne.getData(), null);
        if (expression.getJavaType() == String.class) {
            String valuerFinale = valeurRecherche;
            if (colonne.isSearchWithoutSpaces()) {
                // le siret par exemple no contient pas des espaces
                valuerFinale = valeurRecherche.replace(" ", "");
            }
            predicates.add(cb.like(cb.lower(expression.as(String.class)),
                DatatableSpecification.getLikeFilterValue(valuerFinale),
                DatatableSpecification.ESCAPE_CHAR));
        } else if (expression.getJavaType() == Integer.class) {
            predicates.add(cb.like(expression.as(String.class),
                DatatableSpecification.getLikeFilterValue(valeurRecherche),
                DatatableSpecification.ESCAPE_CHAR));
        } else {
            throw new IllegalArgumentException("La colonne n'a pas le type supporté [String.class|Integer.class] ("
                + expression.getJavaType() + ")");
        }
    }

    return cb.or(predicates.toArray(new Predicate[predicates.size()]));
}
 
Example 59
Project: OperatieBRP   File: LikePredicateBuilder.java   Source Code and License 5 votes vote down vote up
@Override
public Predicate toPredicate(final Root<?> root, final CriteriaQuery<?> query, final CriteriaBuilder cb) {
    // Like en case insensitive
    final Path<String> path = PredicateBuilderUtil.<String>getPath(root, naam);
    final Expression<String> attributeExpression = cb.lower(cb.function(UNACCENT, String.class, path));
    final Expression<String> valueExpression =
            cb.lower(cb.function(UNACCENT, String.class, cb.concat(cb.concat(cb.literal(WILDCARD), cb.literal(value.toString())), cb.literal(WILDCARD))));

    return cb.like(attributeExpression, valueExpression);
}
 
Example 60
Project: sdn-controller-nsc-plugin   File: RedirectionApiUtils.java   Source Code and License 5 votes vote down vote up
public PortGroupEntity txPortGroupEntity(String elementId, String parentId) {
    CriteriaBuilder cb = this.em.getCriteriaBuilder();

    CriteriaQuery<PortGroupEntity> q = cb.createQuery(PortGroupEntity.class);
    Root<PortGroupEntity> r = q.from(PortGroupEntity.class);
    q.where(cb.equal(r.get("elementId"), elementId), cb.equal(r.get("parentId"), parentId));

    try {
        return this.em.createQuery(q).getSingleResult();
    } catch (Exception e) {
        LOG.error("Finding port group entity id '{}' and parentId '{}' ", elementId, parentId, e);
        return null;
    }
}