JPA 2 CriteriaQuery Question

I am just starting out with the JPA 2 Query Request API and find it hard to learn. I looked around the net a bit, but have not yet found good examples / tutorials. Can someone suggest a good tutorial and / or help me with the following simple query that I am trying to fulfill?

I have a class called Transaction that has a link to the account to which it belongs:

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

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

I need to encode a request that receives all transactions for an account, given its account id. Here is my attempt to do this (which obviously does not 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?

Thank. Naresh

+5
source share
1

: -

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

, : - , JPA 2.0

/ JPA, , : - Hibernate

+7

All Articles