我刚刚开始使用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();
}
有人能指出我正确的方向吗?
感谢。 纳雷什
答案 0 :(得分:7)
解决方案: -
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();
}
要理解上述代码的含义,请阅读: - Dynamic, typesafe queries in JPA 2.0
要了解/生成JPA Metamodel,请阅读: - Hibernate Metamodel Generator Reference Guide