Convert this HQL to Criteria - java

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();
}

Related

Implement Hibernate with OrderBy

I want to implement Hibernate query with OrderBy clause. I tried this:
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<OrdersModel> query = builder.createQuery(OrdersModel.class);
Root<OrdersModel> root = query.from(OrdersModel.class);
query.select(root).orderBy(root.get("added"));
Query<OrdersModel> q = session.createQuery(query);
cdList = q.getResultList();
But I have to cast the .orderBy like this query.select(root).orderBy((List<javax.persistence.criteria.Order>) root.get("added"));
Do you know what is the proper way to implement this?
I tried also this:
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<OrdersModel> query = builder.createQuery(OrdersModel.class);
Root<OrdersModel> root = query.from(OrdersModel.class);
query.select(root);
query.orderBy(builder.desc(root.get("added")));
Query<OrdersModel> q = session.createQuery(query).setMaxResults(5);
cdList = q.getResultList();
But the rows order are not displayed properly. The list is not properly sorted.

Run Query with IN clause using Criteria Builder

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

Build criteria query with joins and custom parameters

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.

jpa criteria builder writing simple query

I want to select from database entities with certain price and with certain type but the result list is empty using criteria builder.I came to this code
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery();
Root<Advert> from = criteriaQuery.from(Advert.class);
Predicate predicate1 = criteriaBuilder.ge(from.get("price"), x1);
Predicate predicate2 = criteriaBuilder.le(from.get("price"), x2);
Predicate predicate4 = criteriaBuilder.like(from.get("type"), type);
criteriaQuery.where(criteriaBuilder.and(predicate1, predicate2, predicate4));
TypedQuery<Object> typedQuery = em.createQuery(criteriaQuery);
List<Object> resultList = typedQuery.getResultList();
But the it returns empty List.How to rewrite it correctly?

How to do JPA query with Criteria Clause?

First I want to do a query like
"select count(*) from Post p where p.tag in (tagArray) "
where tagArray is "'tag1','tag2','tag3'".then I'd like to do a paginate query:
query.setFirstResult(int1).setMaxResult(int2);
I don't know how to write this query. I searched the posts ,can't find answers, so can anybody give me any advice? thanks.
Here's sample code:
// get an entity manager
EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpaManager");
EntityManager em = emf.createEntityManager();
// create query
Query query = em.createQuery("select count(*) from Post p where p.tag in (tagArray)") // use parameters here when necessary
.setFirstResult(int1)
.setMaxResults(int2);
// get result
query.getResultList();
Update:
If you want to create query by criteria, try this:
CriteriaBuilder builder = em.getCriteriaBuilder(); // em is as the same the the above
CriteriaQuery<Post> query = builder.createQuery(Post.class);
Root<Post> post = query.from(Post.class);
query.select(post).where(post.get("tag").in("tag1", "tag2", "tag3")); // or pass a tag collection to `in` method
TypedQuery<Post> typedQuery = em.createQuery(query);
List<Post> results = typedQuery.setFirstResult(int1).setMaxResults(int2)
.getResultList();
Thank you very much! Following your instruction, I've done it like this,a little complicated.
public List<Post> findPostBySitePaged(Set sites, Page page) {
List<Post> result = new ArrayList<Post>();
if (sites == null || sites.size() == 0) return result;
try {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Long> cQuery = builder.createQuery(Long.class);
Root<Post> root = cQuery.from(Post.class);
CriteriaQuery<Long> select = cQuery.select(builder.count(root));
select.where(root.get("site").in(sites));
TypedQuery<Long> typedQuery = em.createQuery(select);
Long t = typedQuery.getSingleResult();
int tot = t.intValue() / page.getPageSize() + ((t.intValue() % page.getPageSize()) == 0 ? 0 : 1);
page.setTotal(tot);
CriteriaQuery<Post> criteriaQuery = builder.createQuery(Post.class);
root = criteriaQuery.from(Post.class);
criteriaQuery.select(root).where(root.get("site").in(sites)).orderBy(builder.desc(root.get("createDate")));
TypedQuery<Post> postQuery = em.createQuery(criteriaQuery);
postQuery.setFirstResult((page.getCurrent() - 1) * (page.getPageSize())).setMaxResults(page.getPageSize());
result = postQuery.getResultList();
} catch (Exception e) {
log.error(e.getMessage());
}
return result;
}

Categories

Resources