5

I am just starting out with JPA 2 criteria query API and finding it tough to learn. Looked around the net a bit, but haven't found good examples/tutorials yet. Can someone suggest a good tutorial and/or help me with the following simple query I am trying to code?

I have a class called Transaction that has a reference to the Account that it belongs:

public class Transaction {
    private Account account;
    ...
}

public class Account {
    private Long id;
    ...
}

I need to code a query that gets all the transactions for an account given its account id. Here's my attempt at doing this (which obviously doesn't work):

public List<Transaction> findTransactions(Long accountId) {        
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Transaction> query = builder.createQuery(Transaction.class);
    Root<Transaction> transaction = query.from(Transaction.class);

    // Don't know if I can do "account.id" here
    query.where(builder.equal(transaction.get("account.id"), accountId));
    return entityManager.createQuery(query).getResultList();
}

Can someone point me in the right direction?

Thanks. Naresh

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
Naresh
  • 23,937
  • 33
  • 132
  • 204

1 Answers1

7

Solution:-

public List<Transaction> findTransactions(Long accountId) { 
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<Transaction> query = builder.createQuery(Transaction.class);
        Root<Transaction> _transaction = query.from(Transaction.class);

        Path<Account> _account = _transaction.get(Transaction_.account);
        Path<Long> _accountId = _account.get(Account_.id);

        query.where(builder.equal(_accountId, accountId));
        return entityManager.createQuery(query).getResultList();
    }

To understand the meaning of above code please read:- Dynamic, typesafe queries in JPA 2.0

And to understand/generate JPA Metamodel please read:- Hibernate Metamodel Generator Reference Guide

dira
  • 30,304
  • 14
  • 54
  • 69
  • Thank you becomputer06! This works like a charm. I was able to generate the metamodel quite easily by adding a dependency to hibernate-jpamodelgen to my pom. I was hoping that the m2eclipse plugin would pick it up without any glitches, but it is not doing it right now. If I enable the annotation processor in eclipse I go into a recursive compile cycle! Anyway, the basic issue is solved. Thanks. – Naresh Jan 20 '11 at 23:49