Java Code Examples for javax.persistence.criteria.CriteriaQuery.where()

The following are Jave code examples for showing how to use where() of the javax.persistence.criteria.CriteriaQuery class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: otus_java_2017_10   File: ConnectionHelper.java   Source Code and License Vote up 8 votes
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 2
Project: tap17-muggl-javaee   File: RequestBeanQueries.java   Source Code and License Vote up 7 votes
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_.team);
            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: OperatieBRP   File: VerConvRepositoryImpl.java   Source Code and License Vote up 7 votes
@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 4
Project: OperatieBRP   File: CustomSimpleJpaRepository.java   Source Code and License Vote up 7 votes
/**
 * 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 5
Project: docker-restful-java   File: AuthorizationService.java   Source Code and License Vote up 6 votes
public AuthorizationService(@Context HttpHeaders headers) {
    authorization = false;

    String token = headers.getHeaderString("Authorization");
    if (token != null) {
        try {
            Session session = HibernateUtil.getSessionFactory().openSession();

            CriteriaBuilder builder = session.getCriteriaBuilder();

            CriteriaQuery<User> criteria = builder.createQuery(User.class);
            Root<User> root = criteria.from(User.class);
            criteria.select(root);
            criteria.where(builder.equal(root.get(User_.token), token));

            authenticate = session.createQuery(criteria).getSingleResult();

            if (authenticate != null)
                authorization = true;
        } catch (Exception e) {
        }
    }
}
 
Example 6
Project: cr-private-server   File: ClanService.java   Source Code and License Vote up 6 votes
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 7
Project: tap17-muggl-javaee   File: RequestBean.java   Source Code and License Vote up 6 votes
public List<PlayerDetails> getPlayersByLeagueId(String leagueId) {
    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_.id), leagueId));
            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 8
Project: tap17-muggl-javaee   File: RequestBean.java   Source Code and License Vote up 5 votes
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 9
Project: sucok-framework   File: QueryFormHelper.java   Source Code and License Vote up 5 votes
public static <T> QueryWrapper createQueryWrapper(List<AbstractExpression> expressions) {
	return  (Root<?> root, CriteriaQuery<?> query, CriteriaBuilder cb, boolean sort)-> {
		List<Predicate> predicates = new ArrayList<>();
		expressions.forEach(expression->
			predicates.add(expression.buildJpaPredicate(cb,root))
		);
		Predicate[] array = new Predicate[predicates.size()];
		predicates.toArray(array);
		query.where(array);
	};
}
 
Example 10
Project: tap17-muggl-javaee   File: RequestBean.java   Source Code and License Vote up 5 votes
public List<PlayerDetails> getPlayersByHigherSalary(String name) {
    logger.info("getPlayersByHigherSalary");
    List<Player> players = null;

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

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

            // create a Predicate object that finds players with a salary
            // greater than player1
            Predicate gtPredicate = cb.greaterThan(
                    player1.get(Player_.salary),
                    player2.get(Player_.salary));
            // create a Predicate object that finds the player based on
            // the name parameter
            Predicate equalPredicate = cb.equal(
                    player2.get(Player_.name),
                    name);
            // set the where clause with the predicates
            cq.where(gtPredicate, equalPredicate);
            // set the select clause, and return only unique entries
            cq.select(player1).distinct(true);
            TypedQuery<Player> q = em.createQuery(cq);
            players = q.getResultList();
        }
        return copyPlayersToDetails(players);
    } catch (Exception ex) {
        throw new EJBException(ex);
    }
}
 
Example 11
Project: sdn-controller-nsc-plugin   File: RedirectionApiUtils.java   Source Code and License Vote up 5 votes
public PortEntity txPortEntityByElementId(String elementId) {
    CriteriaBuilder cb = this.em.getCriteriaBuilder();

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

    try {
        return this.em.createQuery(q).getSingleResult();
    } catch (Exception e) {
        LOG.error("Finding Network Element {} ", elementId, e);
        return null;
    }
}
 
Example 12
Project: tasfe-framework   File: BaseRepositoryImpl.java   Source Code and License Vote up 5 votes
@Override
public List<T> findAllByFieldIn(String Field, Iterable<?> values) {
	CriteriaBuilder cb = entityManager.getCriteriaBuilder();
	CriteriaQuery<T> query = cb.createQuery(getDomainClass());
	Root<T> e = query.from(getDomainClass());
	query.where(cb.in(e.get(Field)).value(values));
	return entityManager.createQuery(query).getResultList();
}
 
Example 13
Project: bootstrap   File: PaginationDao.java   Source Code and License Vote up 5 votes
/**
 * Applies the given {@link Specification} to the given {@link CriteriaQuery}.
 */
private <S, T> Root<T> applySpecificationToCriteria(final Root<T> root, final Specification<T> spec, final CriteriaQuery<S> query) {

	Assert.notNull(query, "Query is requested");

	if (spec != null) {
		// There is at least one described filter
		final CriteriaBuilder builder = em.getCriteriaBuilder();
		final Predicate predicate = spec.toPredicate(root, query, builder);

		// There is at least one validated filter
		query.where(predicate);
	}
	return root;
}
 
Example 14
Project: tap17-muggl-javaee   File: RequestBean.java   Source Code and License Vote up 5 votes
public TutoringSession getTodaysSession() {

        // get today's date and trim the time information
        Calendar today = Calendar.getInstance();
        CalendarUtil.stripTime(today);
        // find today's session

        SimpleDateFormat formatter = new SimpleDateFormat("E, MMM d, yyyy");
        logger.log(Level.INFO, "Finding tutoring session for {0}", formatter.format(today.getTime()));

        CriteriaQuery<TutoringSession> cq = cb.createQuery(TutoringSession.class);
        Root<TutoringSession> tutoringSession = cq.from(TutoringSession.class);

        cq.select(tutoringSession);
        cq.where(cb.equal(tutoringSession.get(TutoringSession_.sessionDate), today));
        cq.distinct(true);

        TypedQuery<TutoringSession> q = em.createQuery(cq);
        TutoringSession session;
        try {
            session = q.getSingleResult();
            logger.info("Found session for today.");
        } catch (NoResultException e) {
            logger.info("Today's session not found. Creating a new session.");
            session = new TutoringSession();
            em.persist(session);
        }

        return session;
    }
 
Example 15
Project: otus_java_2017_04   File: UserDataSetDAO.java   Source Code and License Vote up 5 votes
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 16
Project: spring-data-examples   File: AccountRepositoryImpl.java   Source Code and License Vote up 5 votes
@Override
public void removedExpiredAccounts(LocalDate reference) {

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

	query.where(cb.lessThan(account.get("expiryDate").as(Date.class), reference.toDateTimeAtStartOfDay().toDate()));

	for (Account each : em.createQuery(query).getResultList()) {
		em.remove(each);
	}
}
 
Example 17
Project: otus_java_2017_06   File: UserDataSetDAO.java   Source Code and License Vote up 5 votes
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 18
Project: otus_java_2017_06   File: UserDataSetDAO.java   Source Code and License Vote up 5 votes
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 19
Project: linq   File: JpaUtilTests.java   Source Code and License Vote up 4 votes
@Test
@Transactional
public void testFindAll() {
	Assert.notNull(JpaUtil.findAll(User.class), "Not Success.");
	User user = new User();
	user.setId(UUID.randomUUID().toString());
	user.setName("tom");
	User user2 = new User();
	user2.setName("kevin");
	user2.setId(UUID.randomUUID().toString());
	
	JpaUtil.persist(user);
	JpaUtil.persist(user2);
	
	Assert.notEmpty(JpaUtil.findAll(User.class), "Not Success.");
	
	EntityManager em = JpaUtil.getEntityManager(User.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<User> cq = cb.createQuery(User.class);
	Assert.isTrue(JpaUtil.findAll(cq).size() == 2, "Not Success.");
	
	cq.getRoots().clear();
	Root<User> root = cq.from(User.class);
	Assert.isTrue(JpaUtil.findAll(cq).size() == 2, "Not Success.");
	
	cq.where(cb.equal(root.get("name"), "tom"));
	Assert.isTrue(JpaUtil.findAll(cq).size() == 1, "Not Success.");
	
	Pageable pageable = new PageRequest(0, 1);
	Page<User> page = JpaUtil.findAll(User.class, pageable);
	Assert.isTrue(page.getSize() == 1, "Not Success.");
	Assert.isTrue(page.getTotalElements() == 2, "Not Success.");
	Assert.isTrue(page.getTotalPages() == 2, "Not Success.");
	
	Pageable pageable2 = new PageRequest(0, 1, Direction.DESC, "name");
	Page<User> page2 = JpaUtil.findAll(User.class, pageable2);
	Assert.isTrue(page2.getContent().get(0).getName() == "tom", "Not Success.");
	Assert.isTrue(page2.getSize() == 1, "Not Success.");
	Assert.isTrue(page2.getTotalElements() == 2, "Not Success.");
	Assert.isTrue(page2.getTotalPages() == 2, "Not Success.");
	
	Pageable pageable3 = new PageRequest(0, 1, Direction.ASC, "name");
	Page<User> page3 = JpaUtil.findAll(User.class, pageable3);
	Assert.isTrue(page3.getContent().get(0).getName() == "kevin", "Not Success.");
	Assert.isTrue(page3.getSize() == 1, "Not Success.");
	Assert.isTrue(page3.getTotalElements() == 2, "Not Success.");
	Assert.isTrue(page3.getTotalPages() == 2, "Not Success.");
	
	Pageable pageable4 = new PageRequest(0, 1);
	Page<User> page4 = JpaUtil.findAll(cq, pageable4);
	Assert.isTrue(page4.getSize() == 1, "Not Success.");
	Assert.isTrue(page4.getTotalElements() == 1, "Not Success.");
	Assert.isTrue(page4.getTotalPages() == 1, "Not Success.");
	
	Pageable pageable5 = new PageRequest(0, 1, Direction.DESC, "name");
	Page<User> page5 = JpaUtil.findAll(cq, pageable5);
	Assert.isTrue(page5.getContent().get(0).getName() == "tom", "Not Success.");
	Assert.isTrue(page5.getSize() == 1, "Not Success.");
	Assert.isTrue(page5.getTotalElements() == 1, "Not Success.");
	Assert.isTrue(page5.getTotalPages() == 1, "Not Success.");
	
	Pageable pageable6 = new PageRequest(0, 1, Direction.DESC, "name");
	Page<User> page6 = JpaUtil.findAll(cq, pageable6);
	Assert.isTrue(page6.getContent().get(0).getName() == "tom", "Not Success.");
	Assert.isTrue(page6.getSize() == 1, "Not Success.");
	Assert.isTrue(page6.getTotalElements() == 1, "Not Success.");
	Assert.isTrue(page6.getTotalPages() == 1, "Not Success.");
	
	Page<User> page7 = JpaUtil.findAll(cq, null);
	Assert.isTrue(page7.getContent().get(0).getName() == "tom", "Not Success.");
	Assert.isTrue(page7.getSize() == 0, "Not Success.");
	Assert.isTrue(page7.getTotalElements() == 1, "Not Success.");
	Assert.isTrue(page7.getTotalPages() == 1, "Not Success.");
	
	JpaUtil.removeAllInBatch(User.class);
	
}
 
Example 20
Project: datatable-java   File: DatatableDAOImpl.java   Source Code and License Vote up 4 votes
@SuppressWarnings("unchecked")
  private <R> List<R> findAllImpl1(final DatatableQuery<R, T> input, final Specifications<T> specifications,
      final Pageable pageable) {

      // create query
  	final EntityManager entityManager = entityManagerFactory.createEntityManager();
      final CriteriaBuilder qb = entityManager.getCriteriaBuilder();
      final CriteriaQuery<T> cq = qb.createQuery(this.entity);

      // Etablir entité racine
      final Root<T> from = cq.from(this.entity);

      // select
      cq.select(from);

      // where
      if (specifications != null) {
          cq.where(specifications.toPredicate(from, cq, qb));
      }

      // group by
      if (input.getGroupByColumns() != null && !input.getGroupByColumns().isEmpty()) {
          final List<Expression<?>> groupByList = new ArrayList<Expression<?>>();
          DatatableHelper.getExpressions(from, input.getGroupByColumns(), groupByList);
          cq.groupBy(groupByList);
      }

      // order by
      if (pageable != null && pageable.getSort() != null) {
          cq.orderBy(DatatableHelper.getOrderBy(from, qb, pageable));
      }

      // page limit
      final TypedQuery<T> q = entityManager.createQuery(cq);
      if (pageable != null) {
          q.setFirstResult(pageable.getOffset());
          q.setMaxResults(pageable.getPageSize());
      }

      // execute query
      final List<R> ret = (List<R>) q.getResultList();
      entityManager.close();
return ret;
  }