5

我刚开始使用 JPA 2 标准查询 API,发现它很难学习。在网上看了一点,但还没有找到好的例子/教程。有人可以建议一个好的教程和/或帮助我解决我正在尝试编码的以下简单查询吗?

我有一个名为 Transaction 的类,它引用了它所属的 Account:

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

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

我需要编写一个查询来获取给定帐户 ID 的帐户的所有交易。这是我这样做的尝试(这显然行不通):

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

有人可以指出我正确的方向吗?

谢谢。纳雷什

4

1 回答 1

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

于 2011-01-20T06:24:55.113 回答