本文整理了Java中javax.persistence.criteria.CriteriaQuery
类的一些代码示例,展示了CriteriaQuery
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。CriteriaQuery
类的具体详情如下:
包路径:javax.persistence.criteria.CriteriaQuery
类名称:CriteriaQuery
[英]The CriteriaQuery
interface defines functionality that is specific to top-level queries.
[中]CriteriaQuery
接口定义了特定于顶级查询的功能。
代码示例来源:origin: spring-projects/spring-data-examples
public List<User> myCustomBatchOperation() {
CriteriaQuery<User> criteriaQuery = em.getCriteriaBuilder().createQuery(User.class);
criteriaQuery.select(criteriaQuery.from(User.class));
return em.createQuery(criteriaQuery).getResultList();
}
}
代码示例来源:origin: BroadleafCommerce/BroadleafCommerce
@Override
public List<Order> readOrdersByDateRange(final Date startDate, final Date endDate) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Order> criteria = builder.createQuery(Order.class);
Root<OrderImpl> order = criteria.from(OrderImpl.class);
criteria.select(order);
criteria.where(builder.between(order.<Date>get("submitDate"), startDate, endDate));
criteria.orderBy(builder.desc(order.get("submitDate")));
TypedQuery<Order> query = em.createQuery(criteria);
query.setHint(QueryHints.HINT_CACHEABLE, true);
query.setHint(QueryHints.HINT_CACHE_REGION, "query.Order");
return query.getResultList();
}
代码示例来源:origin: BroadleafCommerce/BroadleafCommerce
private TypedQuery<Long> getProductIdsUsingProductOptionByIdQuery(Long productOptionId, boolean count) {
// Set up the criteria query that specifies we want to return Products
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Long> criteria = builder.createQuery(Long.class);
// The root of our search is ProductOptionXref
Root<ProductOptionXrefImpl> productOptionXref = criteria.from(ProductOptionXrefImpl.class);
Join<ProductOptionXref, Product> product = productOptionXref.join("product");
Join<ProductOptionXref, ProductOption> productOption = productOptionXref.join("productOption");
if (count) {
criteria.select(builder.count(product));
} else {
// Product IDs are what we want back
criteria.select(product.get("id").as(Long.class));
}
criteria.distinct(true);
List<Predicate> restrictions = new ArrayList<Predicate>();
restrictions.add(productOption.get("id").in(sandBoxHelper.mergeCloneIds(ProductOptionImpl.class, productOptionId)));
// Execute the query with the restrictions
criteria.where(restrictions.toArray(new Predicate[restrictions.size()]));
return em.createQuery(criteria);
}
代码示例来源:origin: spring-projects/spring-data-examples
@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);
}
}
}
代码示例来源:origin: BroadleafCommerce/BroadleafCommerce
@Override
public List<Page> readOnlineAndIncludedPages(int limit, int offset, String sortBy) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Page> criteria = builder.createQuery(Page.class);
Root<PageImpl> page = criteria.from(PageImpl.class);
criteria.select(page);
criteria.where(builder.and(
builder.or(builder.isFalse(page.get("offlineFlag").as(Boolean.class)), builder.isNull(page.get("offlineFlag").as(Boolean.class))),
builder.or(builder.isFalse(page.get("excludeFromSiteMap").as(Boolean.class)), builder.isNull(page.get("excludeFromSiteMap").as(Boolean.class)))));
criteria.orderBy(builder.asc(page.get(sortBy)));
TypedQuery<Page> query = em.createQuery(criteria);
query.setFirstResult(offset);
query.setMaxResults(limit);
query.setHint(QueryHints.HINT_CACHEABLE, true);
return query.getResultList();
}
代码示例来源:origin: BroadleafCommerce/BroadleafCommerce
@Override
public Long readNumberOfAddresses() {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Long> criteria = builder.createQuery(Long.class);
criteria.select(builder.count(criteria.from(CustomerAddressImpl.class)));
TypedQuery<Long> query = em.createQuery(criteria);
return query.getSingleResult();
}
代码示例来源:origin: hibernate/hibernate-orm
private List<RootEntity> getAllRows(EntityManager em) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<RootEntity> cq = cb.createQuery( RootEntity.class );
Root<RootEntity> c = cq.from( RootEntity.class );
return em.createQuery( cq.select( c ).orderBy( cb.desc( c.get( "status" ) ) ) ).getResultList();
}
代码示例来源:origin: jamesagnew/hapi-fhir
private void findMatchingTagIds(String theResourceName, IIdType theResourceId, Set<Long> tagIds, Class<? extends BaseTag> entityClass) {
{
CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
CriteriaQuery<Tuple> cq = builder.createTupleQuery();
Root<? extends BaseTag> from = cq.from(entityClass);
cq.multiselect(from.get("myTagId").as(Long.class)).distinct(true);
if (theResourceName != null) {
Predicate typePredicate = builder.equal(from.get("myResourceType"), theResourceName);
if (theResourceId != null) {
cq.where(typePredicate, builder.equal(from.get("myResourceId"), myIdHelperService.translateForcedIdToPid(theResourceName, theResourceId.getIdPart())));
} else {
cq.where(typePredicate);
}
}
TypedQuery<Tuple> query = myEntityManager.createQuery(cq);
for (Tuple next : query.getResultList()) {
tagIds.add(next.get(0, Long.class));
}
}
}
代码示例来源:origin: BroadleafCommerce/BroadleafCommerce
@Override
public Long countAllowedValuesForProductOptionById(Long productOptionId) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Long> criteria = builder.createQuery(Long.class);
Root<ProductOptionValueImpl> root = criteria.from(ProductOptionValueImpl.class);
criteria.select(builder.count(root));
List<Predicate> restrictions = new ArrayList<>();
List<Long> mergedIds = sandBoxHelper.mergeCloneIds(ProductOptionImpl.class, productOptionId);
restrictions.add(root.get("productOption").in(mergedIds));
criteria.where(restrictions.toArray(new Predicate[restrictions.size()]));
TypedQuery<Long> query = em.createQuery(criteria);
return query.getSingleResult();
}
代码示例来源:origin: BroadleafCommerce/BroadleafCommerce
@Override
public List<Long> readAllGenericEntityId(Class<?> clazz) {
clazz = DynamicDaoHelperImpl.getNonProxyImplementationClassIfNecessary(clazz);
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Long> criteria = builder.createQuery(Long.class);
Root root = criteria.from(clazz);
criteria.select(root.get(getIdField(clazz).getName()).as(Long.class));
criteria.orderBy(builder.asc(root.get(getIdField(clazz).getName())));
return em.createQuery(criteria).getResultList();
}
代码示例来源:origin: hibernate/hibernate-orm
@Test
public void test_criteria_from_multiple_root_example() {
doInJPA( this::entityManagerFactory, entityManager -> {
String address = "Earth";
String prefix = "J%";
//tag::criteria-from-multiple-root-example[]
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Tuple> criteria = builder.createQuery( Tuple.class );
Root<Person> personRoot = criteria.from( Person.class );
Root<Partner> partnerRoot = criteria.from( Partner.class );
criteria.multiselect( personRoot, partnerRoot );
Predicate personRestriction = builder.and(
builder.equal( personRoot.get( Person_.address ), address ),
builder.isNotEmpty( personRoot.get( Person_.phones ) )
);
Predicate partnerRestriction = builder.and(
builder.like( partnerRoot.get( Partner_.name ), prefix ),
builder.equal( partnerRoot.get( Partner_.version ), 0 )
);
criteria.where( builder.and( personRestriction, partnerRestriction ) );
List<Tuple> tuples = entityManager.createQuery( criteria ).getResultList();
//end::criteria-from-multiple-root-example[]
assertEquals(2, tuples.size());
});
}
代码示例来源:origin: jamesagnew/hapi-fhir
private List<IBaseResource> doHistoryInTransaction(int theFromIndex, int theToIndex) {
List<ResourceHistoryTable> results;
CriteriaBuilder cb = myEntityManager.getCriteriaBuilder();
CriteriaQuery<ResourceHistoryTable> q = cb.createQuery(ResourceHistoryTable.class);
Root<ResourceHistoryTable> from = q.from(ResourceHistoryTable.class);
List<Predicate> predicates = new ArrayList<>();
predicates.add(cb.equal(from.get("myResourceType"), mySearchEntity.getResourceType()));
} else {
predicates.add(cb.equal(from.get("myResourceId"), mySearchEntity.getResourceId()));
predicates.add(cb.greaterThanOrEqualTo(from.get("myUpdated").as(Date.class), mySearchEntity.getLastUpdatedLow()));
predicates.add(cb.lessThanOrEqualTo(from.get("myUpdated").as(Date.class), mySearchEntity.getLastUpdatedHigh()));
q.where(predicates.toArray(new Predicate[predicates.size()]));
q.orderBy(cb.desc(from.get("myUpdated")));
TypedQuery<ResourceHistoryTable> query = myEntityManager.createQuery(q);
query.setFirstResult(theFromIndex);
query.setMaxResults(theToIndex - theFromIndex);
results = query.getResultList();
代码示例来源:origin: hibernate/hibernate-orm
@TestForIssue(jiraKey = "HHH-9296")
@Test
public void selectByParent() {
doInJPA( this::entityManagerFactory, entityManager -> {
Post post = entityManager.find( Post.class, 1 );
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<PostDetails> query = cb.createQuery( PostDetails.class );
Root<PostDetails> root = query.from( PostDetails.class );
query.where( cb.equal( root.get( "post" ), post ) );
final PostDetails result = entityManager.createQuery( query ).getSingleResult();
assertNotNull( result );
});
}
代码示例来源:origin: hibernate/hibernate-orm
@Test
public void test_criteria_from_join_example() {
doInJPA( this::entityManagerFactory, entityManager -> {
//tag::criteria-from-join-example[]
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Phone> criteria = builder.createQuery( Phone.class );
Root<Phone> root = criteria.from( Phone.class );
// Phone.person is a @ManyToOne
Join<Phone, Person> personJoin = root.join( Phone_.person );
// Person.addresses is an @ElementCollection
Join<Person, String> addressesJoin = personJoin.join( Person_.addresses );
criteria.where( builder.isNotEmpty( root.get( Phone_.calls ) ) );
List<Phone> phones = entityManager.createQuery( criteria ).getResultList();
//end::criteria-from-join-example[]
assertEquals(2, phones.size());
});
}
代码示例来源:origin: hibernate/hibernate-orm
@Test
public void test_criteria_param_example() {
doInJPA( this::entityManagerFactory, entityManager -> {
//tag::criteria-param-example[]
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Person> criteria = builder.createQuery( Person.class );
Root<Person> root = criteria.from( Person.class );
ParameterExpression<String> nickNameParameter = builder.parameter( String.class );
criteria.where( builder.equal( root.get( Person_.nickName ), nickNameParameter ) );
TypedQuery<Person> query = entityManager.createQuery( criteria );
query.setParameter( nickNameParameter, "JD" );
List<Person> persons = query.getResultList();
//end::criteria-param-example[]
assertEquals(1, persons.size());
});
}
代码示例来源:origin: hibernate/hibernate-orm
@Test
public void testInClauseParameterPadding() {
sqlStatementInterceptor.clear();
doInJPA( this::entityManagerFactory, entityManager -> {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> query = cb.createQuery( Long.class );
Root<Document> document = query.from( Document.class );
ParameterExpression<List> inClauseParams = cb.parameter( List.class, "ids" );
query
.select( document.get( "id" ) )
.where(
document.get( "id" ).in( inClauseParams )
);
List<Long> ids = entityManager.createQuery( query )
.setParameter(
"ids",
Arrays.asList(
1,
2,
3,
4,
5
)
)
.getResultList();
assertEquals( 1, ids.size() );
} );
assertTrue( sqlStatementInterceptor.getSqlQueries().get( 0 ).endsWith( "in (? , ? , ? , ? , ? , ? , ? , ?)" ) );
}
代码示例来源:origin: BroadleafCommerce/BroadleafCommerce
private CriteriaQuery<SearchRedirect> buildFindSearchRedirectBySearchTermCriteria(String searchTerm) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<SearchRedirect> criteria = builder.createQuery(SearchRedirect.class);
Root<SearchRedirectImpl> redirect = criteria.from(SearchRedirectImpl.class);
List<Predicate> restrictions = new ArrayList<>();
restrictions.add(builder.equal(builder.upper(redirect.<String>get("searchTerm")), searchTerm.toUpperCase()));
// Add the active start/end date restrictions
Date currentDate = getCurrentDateAfterFactoringInDateResolution();
if (isNullActiveStartDateActive) {
restrictions.add(builder.or(builder.isNull(redirect.get("activeStartDate")),
builder.lessThanOrEqualTo(redirect.get("activeStartDate").as(Date.class), currentDate)));
} else {
restrictions.add(builder.and(builder.isNotNull(redirect.get("activeStartDate")),
builder.lessThanOrEqualTo(redirect.get("activeStartDate").as(Date.class), currentDate)));
}
restrictions.add(builder.or(builder.isNull(redirect.get("activeEndDate")),
builder.greaterThan(redirect.get("activeEndDate").as(Date.class), currentDate)));
// Add the restrictions to the criteria query
criteria.select(redirect);
criteria.where(restrictions.toArray(new Predicate[restrictions.size()]));
return criteria.orderBy(builder.asc(redirect.get("searchPriority")));
}
代码示例来源:origin: BroadleafCommerce/BroadleafCommerce
@SuppressWarnings("unchecked")
protected TypedQuery<Serializable> constructQuery(DynamicEntityDao dynamicEntityDao, String ceilingEntity, List<FilterMapping> filterMappings, boolean isCount, boolean isMax, Integer firstResult, Integer maxResults, String maxField) {
CriteriaBuilder criteriaBuilder = dynamicEntityDao.getStandardEntityManager().getCriteriaBuilder();
CriteriaQuery<Serializable> criteria = criteriaBuilder.createQuery(ceilingMarker);
Root<Serializable> original = criteria.from(ceilingClass);
criteria.select(criteriaBuilder.count(original));
} else if (isMax) {
criteria.select(criteriaBuilder.max((Path<Number>) ((Object) original.get(maxField))));
} else {
criteria.select(original);
addRestrictions(ceilingEntity, filterMappings, criteriaBuilder, original, restrictions, sorts, criteria);
criteria.where(restrictions.toArray(new Predicate[restrictions.size()]));
if (!isCount && !isMax) {
criteria.orderBy(sorts.toArray(new Order[sorts.size()]));
Object type = idMetaData.get("type");
if ((idFldName instanceof String) && (type instanceof SingleColumnType)) {
criteria.orderBy(criteriaBuilder.asc(original.get((String) idFldName)));
TypedQuery<Serializable> response = dynamicEntityDao.getStandardEntityManager().createQuery(criteria);
代码示例来源:origin: jamesagnew/hapi-fhir
CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
CriteriaQuery<TagDefinition> cq = builder.createQuery(TagDefinition.class);
Root<TagDefinition> from = cq.from(TagDefinition.class);
cq.where(from.get("myId").in(tagIds));
cq.orderBy(builder.asc(from.get("mySystem")), builder.asc(from.get("myCode")));
TypedQuery<TagDefinition> q = myEntityManager.createQuery(cq);
q.setMaxResults(getConfig().getHardTagListLimit());
for (TagDefinition next : q.getResultList()) {
retVal.add(next.toTag());
代码示例来源:origin: liimaorg/liima
private Query applicationServersForSuggestBox(String input) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<String> q = cb.createQuery(String.class);
Root<ResourceEntity> r = q.from(ResourceEntity.class);
Join<ResourceEntity, ResourceTypeEntity> resType = r.join("resourceType");
Predicate appServerNamePred = cb.like(resType.<String> get("name"), DefaultResourceTypeDefinition.APPLICATIONSERVER.name());
input = input + "%";
q.where(cb.and(appServerNamePred, cb.like(r.<String> get("name"), input)));
q.select(r.<String> get("name"));
q.distinct(true);
q.orderBy(cb.asc(r.get("name")));
return entityManager.createQuery(q);
}
内容来源于网络,如有侵权,请联系作者删除!