Java Code Examples for org.hibernate.Session#getCriteriaBuilder()

The following examples show how to use org.hibernate.Session#getCriteriaBuilder() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ApplicationView.java    From tutorials with MIT License 8 votes vote down vote up
public Long[] projectionRowCount() {
    final Session session = HibernateUtil.getHibernateSession();
    final CriteriaBuilder cb = session.getCriteriaBuilder();
    final CriteriaQuery<Long> cr = cb.createQuery(Long.class);
    final Root<Item> root = cr.from(Item.class);
    cr.select(cb.count(root));
    Query<Long> query = session.createQuery(cr);
    final List<Long> itemProjected = query.getResultList();
    // session.createCriteria(Item.class).setProjection(Projections.rowCount()).list();
    final Long projectedRowCount[] = new Long[itemProjected.size()];
    for (int i = 0; i < itemProjected.size(); i++) {
        projectedRowCount[i] = itemProjected.get(i);
    }
    session.close();
    return projectedRowCount;
}
 
Example 2
Source File: HibernateCriteriaIntegrationTest.java    From tutorials with MIT License 7 votes vote down vote up
@Test
public void givenTargetItemPrice_whenCriteriaDelete_thenDeleteMatched() {

    int targetPrice = 1000;

    Session session = HibernateUtil.getHibernateSession();
    CriteriaBuilder cb = session.getCriteriaBuilder();
    CriteriaDelete<Item> criteriaDelete = cb.createCriteriaDelete(Item.class);
    Root<Item> root = criteriaDelete.from(Item.class);
    criteriaDelete.where(cb.greaterThan(root.get("itemPrice"), targetPrice));

    Transaction transaction = session.beginTransaction();
    session.createQuery(criteriaDelete).executeUpdate();
    transaction.commit();

    List<Item> deletedItem = session.createQuery("FROM Item WHERE itemPrice > " + targetPrice, Item.class).list();
    assertTrue(deletedItem.isEmpty());

}
 
Example 3
Source File: ApplicationView.java    From tutorials with MIT License 6 votes vote down vote up
public String[] lessThanCriteria() {
    final Session session = HibernateUtil.getHibernateSession();
    final CriteriaBuilder cb = session.getCriteriaBuilder();
    final CriteriaQuery<Item> cr = cb.createQuery(Item.class);
    final Root<Item> root = cr.from(Item.class);
    cr.select(root)
        .where(cb.lt(root.get("itemPrice"), 1000));
    // cr.add(Restrictions.lt("itemPrice", 1000));
    Query<Item> query = session.createQuery(cr);
    final List<Item> lessThanItemsList = query.getResultList();
    final String lessThanItems[] = new String[lessThanItemsList.size()];
    for (int i = 0; i < lessThanItemsList.size(); i++) {
        lessThanItems[i] = lessThanItemsList.get(i)
            .getItemName();
    }
    session.close();
    return lessThanItems;
}
 
Example 4
Source File: ApplicationView.java    From tutorials with MIT License 6 votes vote down vote up
public String[] sortingCriteria() {
    final Session session = HibernateUtil.getHibernateSession();
    final CriteriaBuilder cb = session.getCriteriaBuilder();
    final CriteriaQuery<Item> cr = cb.createQuery(Item.class);
    final Root<Item> root = cr.from(Item.class);
    cr.select(root);
    cr.orderBy(cb.asc(root.get("itemName")), cb.desc(root.get("itemPrice")));
    // cr.addOrder(Order.asc("itemName"));
    // cr.addOrder(Order.desc("itemPrice")).list();
    Query<Item> query = session.createQuery(cr);
    final List<Item> sortedItemsList = query.getResultList();
    final String sortedItems[] = new String[sortedItemsList.size()];
    for (int i = 0; i < sortedItemsList.size(); i++) {
        sortedItems[i] = sortedItemsList.get(i)
            .getItemName();
    }
    session.close();
    return sortedItems;
}
 
Example 5
Source File: ApplicationView.java    From tutorials with MIT License 6 votes vote down vote up
public String[] andLogicalCriteria() {
    final Session session = HibernateUtil.getHibernateSession();
    final CriteriaBuilder cb = session.getCriteriaBuilder();
    final CriteriaQuery<Item> cr = cb.createQuery(Item.class);
    final Root<Item> root = cr.from(Item.class);
    Predicate greaterThanPrice = cb.gt(root.get("itemPrice"), 1000);
    Predicate chairItems = cb.like(root.get("itemName"), "Chair%");
    cr.select(root)
        .where(cb.and(greaterThanPrice, chairItems));
    // final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000);
    // final Criterion chairItems = Restrictions.like("itemName", "Chair%");
    // final LogicalExpression andExample = Restrictions.and(greaterThanPrice, chairItems);
    // cr.add(andExample);
    Query<Item> query = session.createQuery(cr);
    final List<Item> andItemsList = query.getResultList();
    final String andItems[] = new String[andItemsList.size()];
    for (int i = 0; i < andItemsList.size(); i++) {
        andItems[i] = andItemsList.get(i)
            .getItemName();
    }
    session.close();
    return andItems;
}
 
Example 6
Source File: ApplicationView.java    From tutorials with MIT License 6 votes vote down vote up
public String[] twoCriteria() {
    final Session session = HibernateUtil.getHibernateSession();
    final CriteriaBuilder cb = session.getCriteriaBuilder();
    final CriteriaQuery<Item> cr = cb.createQuery(Item.class);
    final Root<Item> root = cr.from(Item.class);
    Predicate[] predicates = new Predicate[2];
    predicates[0] = cb.isNull(root.get("itemDescription"));
    predicates[1] = cb.like(root.get("itemName"), "chair%");
    cr.select(root)
        .where(predicates);
    // cr.add(Restrictions.isNull("itemDescription"));
    // cr.add(Restrictions.like("itemName", "chair%"));
    Query<Item> query = session.createQuery(cr);
    final List<Item> notNullItemsList = query.getResultList();
    final String notNullDescItems[] = new String[notNullItemsList.size()];
    for (int i = 0; i < notNullItemsList.size(); i++) {
        notNullDescItems[i] = notNullItemsList.get(i)
            .getItemName();
    }
    session.close();
    return notNullDescItems;
}
 
Example 7
Source File: ApplicationView.java    From tutorials with MIT License 6 votes vote down vote up
public String[] notNullCriteria() {
    final Session session = HibernateUtil.getHibernateSession();
    final CriteriaBuilder cb = session.getCriteriaBuilder();
    final CriteriaQuery<Item> cr = cb.createQuery(Item.class);
    final Root<Item> root = cr.from(Item.class);
    cr.select(root)
        .where(cb.isNotNull(root.get("itemDescription")));
    // cr.add(Restrictions.isNotNull("itemDescription"));
    Query<Item> query = session.createQuery(cr);
    final List<Item> notNullItemsList = query.getResultList();
    final String notNullDescItems[] = new String[notNullItemsList.size()];
    for (int i = 0; i < notNullItemsList.size(); i++) {
        notNullDescItems[i] = notNullItemsList.get(i)
            .getItemName();
    }
    session.close();
    return notNullDescItems;
}
 
Example 8
Source File: ApplicationView.java    From tutorials with MIT License 6 votes vote down vote up
public String[] nullCriteria() {
    final Session session = HibernateUtil.getHibernateSession();
    final CriteriaBuilder cb = session.getCriteriaBuilder();
    final CriteriaQuery<Item> cr = cb.createQuery(Item.class);
    final Root<Item> root = cr.from(Item.class);
    cr.select(root)
        .where(cb.isNull(root.get("itemDescription")));
    // cr.add(Restrictions.isNull("itemDescription"));
    Query<Item> query = session.createQuery(cr);
    final List<Item> nullItemsList = query.getResultList();
    final String nullDescItems[] = new String[nullItemsList.size()];
    for (int i = 0; i < nullItemsList.size(); i++) {
        nullDescItems[i] = nullItemsList.get(i)
            .getItemName();
    }
    session.close();
    return nullDescItems;
}
 
Example 9
Source File: ApplicationView.java    From tutorials with MIT License 6 votes vote down vote up
public String[] betweenCriteria() {
    final Session session = HibernateUtil.getHibernateSession();
    final CriteriaBuilder cb = session.getCriteriaBuilder();
    final CriteriaQuery<Item> cr = cb.createQuery(Item.class);
    final Root<Item> root = cr.from(Item.class);
    cr.select(root)
        .where(cb.between(root.get("itemPrice"), 100, 200));
    // cr.add(Restrictions.between("itemPrice", 100, 200));
    Query<Item> query = session.createQuery(cr);
    final List<Item> betweenItemsList = query.getResultList();
    final String betweenItems[] = new String[betweenItemsList.size()];
    for (int i = 0; i < betweenItemsList.size(); i++) {
        betweenItems[i] = betweenItemsList.get(i)
            .getItemName();
    }
    session.close();
    return betweenItems;
}
 
Example 10
Source File: ApplicationView.java    From tutorials with MIT License 6 votes vote down vote up
public String[] likeCaseCriteria() {
    final Session session = HibernateUtil.getHibernateSession();
    final CriteriaBuilder cb = session.getCriteriaBuilder();
    final CriteriaQuery<Item> cr = cb.createQuery(Item.class);
    final Root<Item> root = cr.from(Item.class);
    cr.select(root)
        .where(cb.like(cb.lower(root.get("itemName")), "%chair%"));
    // cr.add(Restrictions.ilike("itemName", "%Chair%"));
    Query<Item> query = session.createQuery(cr);
    final List<Item> ilikeItemsList = query.getResultList();
    final String ilikeItems[] = new String[ilikeItemsList.size()];
    for (int i = 0; i < ilikeItemsList.size(); i++) {
        ilikeItems[i] = ilikeItemsList.get(i)
            .getItemName();
    }
    session.close();
    return ilikeItems;
}
 
Example 11
Source File: ApplicationView.java    From tutorials with MIT License 6 votes vote down vote up
public String[] likeCriteria() {
    final Session session = HibernateUtil.getHibernateSession();
    final CriteriaBuilder cb = session.getCriteriaBuilder();
    final CriteriaQuery<Item> cr = cb.createQuery(Item.class);
    final Root<Item> root = cr.from(Item.class);
    cr.select(root)
        .where(cb.like(root.get("itemName"), "%chair%"));
    // cr.add(Restrictions.like("itemName", "%chair%"));
    Query<Item> query = session.createQuery(cr);
    final List<Item> likeItemsList = query.getResultList();
    final String likeItems[] = new String[likeItemsList.size()];
    for (int i = 0; i < likeItemsList.size(); i++) {
        likeItems[i] = likeItemsList.get(i)
            .getItemName();
    }
    session.close();
    return likeItems;
}
 
Example 12
Source File: ApplicationView.java    From tutorials with MIT License 6 votes vote down vote up
public String[] greaterThanCriteria() {
    final Session session = HibernateUtil.getHibernateSession();
    final CriteriaBuilder cb = session.getCriteriaBuilder();
    final CriteriaQuery<Item> cr = cb.createQuery(Item.class);
    final Root<Item> root = cr.from(Item.class);
    cr.select(root)
        .where(cb.gt(root.get("itemPrice"), 1000));
    // cr.add(Restrictions.gt("itemPrice", 1000));
    Query<Item> query = session.createQuery(cr);
    final List<Item> greaterThanItemsList = query.getResultList();
    final String greaterThanItems[] = new String[greaterThanItemsList.size()];
    for (int i = 0; i < greaterThanItemsList.size(); i++) {
        greaterThanItems[i] = greaterThanItemsList.get(i)
            .getItemName();
    }
    session.close();
    return greaterThanItems;
}
 
Example 13
Source File: ApplicationView.java    From tutorials with MIT License 6 votes vote down vote up
public Double[] projectionAverage() {
    final Session session = HibernateUtil.getHibernateSession();
    final CriteriaBuilder cb = session.getCriteriaBuilder();
    final CriteriaQuery<Double> cr = cb.createQuery(Double.class);
    final Root<Item> root = cr.from(Item.class);
    cr.select(cb.avg(root.get("itemPrice")));
    Query<Double> query = session.createQuery(cr);
    final List avgItemPriceList = query.getResultList();
    // session.createCriteria(Item.class).setProjection(Projections.projectionList().add(Projections.avg("itemPrice"))).list();

    final Double avgItemPrice[] = new Double[avgItemPriceList.size()];
    for (int i = 0; i < avgItemPriceList.size(); i++) {
        avgItemPrice[i] = (Double) avgItemPriceList.get(i);
    }
    session.close();
    return avgItemPrice;
}
 
Example 14
Source File: RdbmsUtils.java    From modeldb with Apache License 2.0 6 votes vote down vote up
/**
 * Return the data count base on the criteria query
 *
 * @param session : hibernate session
 * @param root : entity root which is further used for getting sub filed path from it and set in
 *     criteria where clause. Ex: Root<ProjectEntity> projectRoot =
 *     criteriaQuery.from(ProjectEntity.class);
 * @param criteria : Hibernate criteria query reference for further process
 * @param <T> : T = entity name like ProjectEntity, DatasetEntity, ExperimentEntity etc.
 * @return {@link Long} : total records count
 */
public static <T> long count(Session session, Root<T> root, CriteriaQuery<T> criteria) {
  final CriteriaBuilder builder = session.getCriteriaBuilder();
  final CriteriaQuery<Long> countCriteria = builder.createQuery(Long.class);

  countCriteria.select(builder.count(root));
  countCriteria.getRoots().addAll(criteria.getRoots());

  final Predicate whereRestriction = criteria.getRestriction();
  if (whereRestriction != null) {
    countCriteria.where(whereRestriction);
  }

  final Predicate groupRestriction = criteria.getGroupRestriction();
  if (groupRestriction != null) {
    countCriteria.having(groupRestriction);
  }

  countCriteria.groupBy(criteria.getGroupList());
  countCriteria.distinct(criteria.isDistinct());
  return session.createQuery(countCriteria).getSingleResult();
}
 
Example 15
Source File: DefaultProjectManager.java    From onedev with MIT License 6 votes vote down vote up
private CriteriaQuery<Project> buildCriteriaQuery(Session session, EntityQuery<Project> projectQuery) {
	CriteriaBuilder builder = session.getCriteriaBuilder();
	CriteriaQuery<Project> query = builder.createQuery(Project.class);
	Root<Project> root = query.from(Project.class);
	query.select(root);
	
	query.where(getPredicates(projectQuery.getCriteria(), root, builder));

	List<javax.persistence.criteria.Order> orders = new ArrayList<>();
	for (EntitySort sort: projectQuery.getSorts()) {
		if (sort.getDirection() == Direction.ASCENDING)
			orders.add(builder.asc(ProjectQuery.getPath(root, Project.ORDER_FIELDS.get(sort.getField()))));
		else
			orders.add(builder.desc(ProjectQuery.getPath(root, Project.ORDER_FIELDS.get(sort.getField()))));
	}

	if (orders.isEmpty())
		orders.add(builder.desc(ProjectQuery.getPath(root, Project.PROP_UPDATE_DATE)));
	query.orderBy(orders);
	
	return query;
}
 
Example 16
Source File: HibernateTest.java    From mybatis-test with Apache License 2.0 5 votes vote down vote up
@Test
public void testJpaCriteria() throws ParseException {
    System.out.println("---------------------------✨ JPA Criteria ✨------------------------");

    Session session = null;
    try {
        session = buildSessionFactory.openSession();
        CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
        CriteriaQuery<Article> criteriaQuery = criteriaBuilder.createQuery(Article.class);

        // 定义 FROM 子句
        Root<Article> article = criteriaQuery.from(Article.class);

        // 构建查询条件
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
        Predicate greaterThan = criteriaBuilder.greaterThan(article.get("createTime"), sdf.parse("2018.06.10"));
        Predicate equal = criteriaBuilder.equal(article.get("author"), "coolblog.xyz");

        // 通过具有语义化的方法构建 SQL,等价于 SELECT ... FROM article WHERE ... AND ...
        criteriaQuery.select(article).where(equal, greaterThan);

        Query<Article> query = session.createQuery(criteriaQuery);
        List<Article> articles = query.getResultList();

        System.out.println("JPA Criteria Query Result: ");
        articles.forEach(System.out::println);
    } finally {
        if (Objects.nonNull(session)) {
            session.close();
        }
    }

}
 
Example 17
Source File: ApplicationView.java    From tutorials with MIT License 5 votes vote down vote up
public boolean checkIfCriteriaTimeLower() {
    final Session session = HibernateUtil.getHibernateSession();
    final CriteriaBuilder cb = session.getCriteriaBuilder();
    final CriteriaQuery<Item> cr = cb.createQuery(Item.class);
    final Root<Item> root = cr.from(Item.class);

    // calculate the time taken by criteria
    final long startTimeCriteria = System.nanoTime();
    cr.select(root)
        .where(cb.like(root.get("itemName"), "%item One%"));
    // .add(Restrictions.like("itemName", "%item One%"));
    Query<Item> query = session.createQuery(cr);

    final List<Item> results = query.getResultList();
    final long endTimeCriteria = System.nanoTime();
    final long durationCriteria = (endTimeCriteria - startTimeCriteria) / 1000;

    // calculate the time taken by HQL
    final long startTimeHQL = System.nanoTime();
    session.beginTransaction();
    final List<Item> items = session.createQuery("FROM Item where itemName like '%item One%'")
        .list();
    final long endTimeHQL = System.nanoTime();
    final long durationHQL = (endTimeHQL - startTimeHQL) / 1000;

    if (durationCriteria > durationHQL) {
        return false;
    } else {
        return true;
    }
}
 
Example 18
Source File: DefaultBuildManager.java    From onedev with MIT License 5 votes vote down vote up
private CriteriaQuery<Build> buildCriteriaQuery(@Nullable Project project, 
		Session session,  EntityQuery<Build> buildQuery) {
	CriteriaBuilder builder = session.getCriteriaBuilder();
	CriteriaQuery<Build> query = builder.createQuery(Build.class);
	Root<Build> root = query.from(Build.class);
	query.select(root);
	
	query.where(getPredicates(project, buildQuery.getCriteria(), root, builder));

	applyOrders(root, query, builder, buildQuery);
	
	return query;
}
 
Example 19
Source File: DefaultIssueManager.java    From onedev with MIT License 5 votes vote down vote up
private CriteriaQuery<Issue> buildCriteriaQuery(@Nullable Project project, 
		Session session, EntityQuery<Issue> issueQuery) {
	CriteriaBuilder builder = session.getCriteriaBuilder();
	CriteriaQuery<Issue> query = builder.createQuery(Issue.class);
	Root<Issue> root = query.from(Issue.class);
	
	query.where(getPredicates(project, issueQuery.getCriteria(), root, builder));

	List<javax.persistence.criteria.Order> orders = new ArrayList<>();
	for (EntitySort sort: issueQuery.getSorts()) {
		if (Issue.ORDER_FIELDS.containsKey(sort.getField())) {
			if (sort.getDirection() == Direction.ASCENDING)
				orders.add(builder.asc(IssueQuery.getPath(root, Issue.ORDER_FIELDS.get(sort.getField()))));
			else
				orders.add(builder.desc(IssueQuery.getPath(root, Issue.ORDER_FIELDS.get(sort.getField()))));
		} else {
			Join<Issue, IssueField> join = root.join(Issue.PROP_FIELDS, JoinType.LEFT);
			join.on(builder.equal(join.get(IssueField.PROP_NAME), sort.getField()));
			if (sort.getDirection() == Direction.ASCENDING)
				orders.add(builder.asc(join.get(IssueField.PROP_ORDINAL)));
			else
				orders.add(builder.desc(join.get(IssueField.PROP_ORDINAL)));
		}
	}

	if (orders.isEmpty()) {
		orders.add(builder.desc(IssueQuery.getPath(root, Issue.PROP_LAST_UPDATE + "." + LastUpdate.PROP_DATE)));
	}
	query.orderBy(orders);
	
	return query;
}
 
Example 20
Source File: DefaultPullRequestManager.java    From onedev with MIT License 5 votes vote down vote up
private CriteriaQuery<PullRequest> buildCriteriaQuery(Session session, @Nullable Project targetProject, 
		EntityQuery<PullRequest> requestQuery) {
	CriteriaBuilder builder = session.getCriteriaBuilder();
	CriteriaQuery<PullRequest> query = builder.createQuery(PullRequest.class);
	Root<PullRequest> root = query.from(PullRequest.class);
	
	query.where(getPredicates(targetProject, requestQuery.getCriteria(), root, builder));

	List<javax.persistence.criteria.Order> orders = new ArrayList<>();
	for (EntitySort sort: requestQuery.getSorts()) {
		if (sort.getDirection() == Direction.ASCENDING) {
			orders.add(builder.asc(PullRequestQuery.getPath(
					root, PullRequest.ORDER_FIELDS.get(sort.getField()))));
		} else {
			orders.add(builder.desc(PullRequestQuery.getPath(
					root, PullRequest.ORDER_FIELDS.get(sort.getField()))));
		}
	}

	if (orders.isEmpty()) {
		orders.add(builder.asc(PullRequestQuery.getPath(root, PullRequest.PROP_CLOSE_INFO + "." + CloseInfo.PROP_STATUS)));
		orders.add(builder.desc(PullRequestQuery.getPath(root, PullRequest.PROP_LAST_UPDATE + "." + LastUpdate.PROP_DATE)));
	}
	query.orderBy(orders);
	
	return query;
}