0

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?
Mikko Maunu
  • 41,366
  • 10
  • 132
  • 135
user2586917
  • 762
  • 1
  • 9
  • 26

2 Answers2

2

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();
guardian
  • 429
  • 3
  • 5
  • Thanks @guardian, this worked well, I have another more complex one as well :-) here http://stackoverflow.com/questions/24909975/convert-this-hql-query-to-criteria – user2586917 Jul 23 '14 at 12:02
  • I think Ramzan Zafars Solution is far superior to this one, code wise. – Ota Jul 23 '14 at 12:13
1

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();
    }
Ramzan Zafar
  • 1,562
  • 2
  • 17
  • 18
  • Why the second `.createCriteria("auditAccount")` call? – Ota Jul 23 '14 at 09:54
  • 1
    as he need to check on auditAccount which is the child object of AuditRecordEntity as he mentioned in his question auditRecord.auditAccount.accountId – Ramzan Zafar Jul 23 '14 at 10:01