I need some help to run the query bellow, using the CriteriaBuilder aproach:
select count(*) from TABLE_VIEW_SEARCH where
person_ID in (select person_ID from TABLE_PERSON
where region_ID = 1001) and postal_cd ='AL';
I try this but it failed:
CriteriaBuilder cb = ..;
CriteriaQuery<Long> criteriaQuery= cb.createQuery(Long.class);
Root<ViewSearchEntity> from= criteriaQuery.from(ViewSearchEntity.class);
Subquery<Long> subQuery = criteriaQuery.subquery(Long.class);
Root<PersonEntity> subFrom = subQuery .from(PersonEntity.class);
subQuery .where(cb.equal(subFrom.get(PersonEntity_.region_ID ), region_ID ));
criteriaQuery.select(cb.count(from));
criteriaQuery.where(meFrom.in(subQuery );
TypedQuery<Long> query = getEntityManager().createQuery(criteriaQuery);
Long result = query.getSingleResult();
I reach a solution, basicaly I managed to do the join condition:
CriteriaBuilder cb = ..;
CriteriaQuery<Long> criteriaQuery= cb.createQuery(Long.class);
Root<ViewSearchEntity> from= criteriaQuery.from(ViewSearchEntity.class);
Predicate predicate1 = cb.equal(from.get(ViewSearchEntity.postal_cd),"AL");
Subquery<Long> subQuery = criteriaQuery.subquery(Long.class);
Root<PersonEntity> subRoot = subQuery.from(PersonEntity.class);
Join<PersonEntity, RegionEntity_> region= subRoot.join(RegionEntity_.region);
subQuery.select(region.get(RegionEntity_.regionId)).where(
cb.equal(subRoot.get(PersonEntity_.region), regionId));
Predicate predicateInClause = root.get(ViewSearchEntity_.postal_cd).in(subQuery);
return getEntityManager().createQuery(criteriaQuery.select(cb.count(root)).where(predicate1,predicateInClause)).getEntityManager().createQuery(criteriaQuery.select(cb.count(root)).where(predicate1,predicateInClause))
Something like this. I cannot give you a query, due to missing entity names. However, I recommend to read this Criteria API subselect
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery(TABLE_VIEW_SEARCH.class);
Root root = cq.from(TABLE_VIEW_SEARCH.class);
Subquery sub = cq.subquery(TABLE_PERSON.class);
Root subRoot = sub.from(TABLE_PERSON.class);
SetJoin<TABLE_PERSON, TABLE_VIEW_SEARCH> subViewSearch =
subRoot.join(TABLE_PERSON.tableViewSearch);
sub.select(cb.equal(subRoot.get(TABLE_PERSON.region_ID), 1001));
cq.where(cb.equal(root.get("postal_cd"), "AL"));
TypedQuery query = em.createQuery(cq);
List result = query.getResultList();
You can use this method, once you have metamodel generation dependency declared:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>
</dependency>
Rebuild your project with maven after you add this dependency, and then you can do this:
EntityName_.attribute
Related
I need to build following query using JPA and criteria query but I stuck on join conditions. The query is:
SELECT p.*
FROM output cu
JOIN user ur ON cu.id = ur.id AND cu.key = ur.key
JOIN product p ON cu.id = p.id AND cu.key = p.key
WHERE p.refreshtimestamp IS NOT NULL AND cu.active = true
So far I have following, but how to apply join conditions:
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Output> cq = cb.createQuery(Output.class);
Root<Output> output= cq.from(Output.class);
Join<Output, User> user = output.join("user", JoinType.INNER);
Join<User, Product> product = user.join("product", JoinType.INNER);
Any help will be appreciated
Following should help.
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Product> criteria = builder.createQuery(Product.class);
Root<Output> outputRoot = criteria.from(Output.class);
Root<User> userRoot = criteria.from(User.class);
Root<Product> productRoot = criteria.from(Product.class);
Predicate[] predictes = {
builder.equal(outputRoot.get("id"), userRoot.get("key")),
builder.equal(productRoot.get("id"), userRoot.get("key")),
builder.notEqual(productRoot.get("refreshtimestamp"), null), // not sure about null
builder.equal(outputRoot.get("active"), true)
};
criteria.select(productRoot);
criteria.where(builder.and(predicates));
Although this would produce cross joins query, it will work because of where clause making it work like inner join as you require.
I have a problem with Criteria API (JPA 2.0). I want to write code which returns the same result as query (select count from (select count from ... group by ...)):
SELECT COUNT(*) FROM (
SELECT COUNT(*) FROM a
LEFT JOIN p ON a.id = p.a_id
LEFT JOIN s ON a.id = s.a_id
WHERE ... GROUP BY s.r_id
)
I wrote something like this:
CriteriaBuilder builder = slave.getCriteriaBuilder();
CriteriaQuery<Long> query = builder.createQuery(Long.class);
Subquery<Long> subquery = query.subquery(Long.class);
Root<A> entity = subquery.from(A.class);
Join<A, P> pJoin = entity.join("p", JoinType.LEFT);
Join<A, S> sJoin = entity.join("s", JoinType.LEFT);
subquery.select(builder.count(entity));
subquery.where(/*where predicate*/);
subquery.groupBy(sJoin.get("r"));
query.select(builder.count(subquery));
Long result = slave.createQuery(query).getSingleResult();
But I get the exception:
java.lang.IllegalStateException: No criteria query roots were specified
What am I doing wrong here?
I need to get from DB items in a date range ("created"). Query is correct (i check it in HeidiSQL) and select right rows from DB, but typedQuery.resultList() always has 0 items.
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<CurrencyConvertionRate> criteriaQuery = criteriaBuilder.createQuery(CurrencyConvertionRate.class);
Root<CurrencyConvertionRate> root = criteriaQuery.from(CurrencyConvertionRate.class);
List<Predicate> criteria = new ArrayList<Predicate>();
<Timestamp>get(created)={}", criteriaBuilder.greaterThanOrEqualTo(root.<Timestamp>get("created"), dateFrom).toString());
log.debug("criteriaBuilder.lessThanOrEqualTo(root.<Timestamp>get(created), dateTo={}", criteriaBuilder.lessThanOrEqualTo(root.<Timestamp>get("created"), dateTo).toString());
log.debug("root.get(currencyCode).in(currencyList)={}", root.get("currencyCode").in(currencyList).toString());
criteria.add(criteriaBuilder.greaterThanOrEqualTo(root.<Timestamp>get("created"), dateFrom));
criteria.add(criteriaBuilder.lessThanOrEqualTo(root.<Timestamp>get("created"), dateTo));
criteria.add(root.get("currencyCode").in(currencyList));
CriteriaQuery<CurrencyConvertionRate> select = criteriaQuery.select(root);
select.where(criteriaBuilder.and(criteria.toArray(new Predicate[0])));
TypedQuery<CurrencyConvertionRate> typedQuery = entityManager.createQuery(select);
return typedQuery.getResultList();
I have the following HQL statement:
select auditRecord from AuditRecordEntity auditRecord where auditRecord.auditAccount.accountId = :accountId
I'd like to convert it to use the javax.persistence.criteria.CriteriaBuilder, but am unsure what do do, any help is much appreciated!
CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
CriteriaQuery<Object> query = builder.createQuery();
Root<AuditRecordEntity> root = query.from(AuditRecordEntity.class);
// what next?
Try this:
CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
CriteriaQuery<AuditRecordEntity> criteriaQuery = criteriaBuilder.createQuery(AuditRecordEntity.class);
Root<AuditRecordEntity> root = criteriaQuery.from(AuditRecordEntity.class);
Predicate predicate = criteriaBuilder.equal(root.get("auditAccount").get("accountId"), accountId);
criteriaQuery.where(predicate);
TypedQuery<AuditRecordEntity> query = em.createQuery(criteriaQuery);
return query.getSingleResult();
you can do it like following
public List<UserProfile> getAuditRecords(String acountId) {
Criteria auditCriteria = session.createCriteria(AuditRecordEntity.class);
auditCriteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
auditCriteria.createCriteria("auditAccount").add(Restrictions.eq("accountId ",acountId));
return auditCriteria .list();
}
I'm trying to crete Criteria API query with CONTAINS function(MS SQL):
select * from com.t_person where contains(last_name,'xxx')
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Person> cq = cb.createQuery(Person.class);
Root<Person> root = cq.from(Person.class);
Expression<Boolean> function = cb.function("CONTAINS", Boolean.class,
root.<String>get("lastName"),cb.parameter(String.class, "containsCondition"));
cq.where(function);
TypedQuery<Person> query = em.createQuery(cq);
query.setParameter("containsCondition", lastName);
return query.getResultList();
But getting exception:
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected AST node:
Any help?
If you want to stick with using CONTAINS, it should be something like this:
//Get criteria builder
CriteriaBuilder cb = em.getCriteriaBuilder();
//Create the CriteriaQuery for Person object
CriteriaQuery<Person> query = cb.createQuery(Person.class);
//From clause
Root<Person> personRoot = query.from(Person.class);
//Where clause
query.where(
cb.function(
"CONTAINS", Boolean.class,
//assuming 'lastName' is the property on the Person Java object that is mapped to the last_name column on the Person table.
personRoot.<String>get("lastName"),
//Add a named parameter called containsCondition
cb.parameter(String.class, "containsCondition")));
TypedQuery<Person> tq = em.createQuery(query);
tq.setParameter("containsCondition", "%näh%");
List<Person> people = tq.getResultList();
It seems like some of your code is missing from your question so I'm making a few assumptions in this snippet.
You could try using the CriteriaBuilder like function instead of the CONTAINS function:
//Get criteria builder
CriteriaBuilder cb = em.getCriteriaBuilder();
//Create the CriteriaQuery for Person object
CriteriaQuery<Person> query = cb.createQuery(Person.class);
//From clause
Root<Person> personRoot = query.from(Person.class);
//Where clause
query.where(
//Like predicate
cb.like(
//assuming 'lastName' is the property on the Person Java object that is mapped to the last_name column on the Person table.
personRoot.<String>get("lastName"),
//Add a named parameter called likeCondition
cb.parameter(String.class, "likeCondition")));
TypedQuery<Person> tq = em.createQuery(query);
tq.setParameter("likeCondition", "%Doe%");
List<Person> people = tq.getResultList();
This should result in a query similar to:
select p from PERSON p where p.last_name like '%Doe%';