我有2个具有一对多关系的课程。 客户(类)有很多交易(类)
public class Customer {
@Id
private Long clientId;
private String name;
@OneToMany
private List<Transactions> transactions;
}
public class Transactions {
@JoinColumn(name = "clientId")
private Transactions transactions;
private int statusType;
private String amount;
}
int dynamicValue = 1003;
CriteriaQuery<Customer> criteriaQuery = getBuilder().createQuery(Customer.class);
Root<Customer> customersRoot = criteriaQuery.from(Customer.class);
Join<Customer, Transactions> transactions = customersRoot.join("transactions");
TypedQuery<Customer> query = em.createQuery(criteriaQuery.select(customerRoot).where(getBuilder().equal(transactions.get("statusType"), dynamicValue)));
List<Customer> customerList = (List<Customer>) query.getResultList();
我有2个来自数据库的数据: 客户表
ClientId | Name |
1 | James |
2 | Eli |
交易记录表:
ClientId | Status Type| Amount| TransactionId |
1 | 1002 | 100 | 1 |
1 | 1003 | 200 | 2 |
我需要在上面进行查询以接受多个参数(动态)。这些参数将来自客户的属性(例如名称),一些参数将来自Transactions类。但是,当我尝试执行上面的代码时,它总是在我的数据库中获得第一条记录(1002),这是不正确的。
请给我一点启发。 问题:
答案 0 :(得分:0)
您当前正在传递文字。这与参数不同。参见http://www.datanucleus.org:15080/products/accessplatform_5_2/jpa/query.html#_criteria_api_parameters
将代码更改为
CriteriaQuery<Customer> criteriaQuery = getBuilder().createQuery(Customer.class);
Root<Customer> customersRoot = criteriaQuery.from(Customer.class);
Join<Customer, Transactions> transactions = customersRoot.join("transactions");
ParameterExpression param = getBuilder().parameter(int.class, "myParam");
TypedQuery<Customer> query = em.createQuery(criteriaQuery.select(customerRoot).where(getBuilder().equal(transactions.get("statusType"), param)));
// Execute with first parameter value
query.setParameter("myParam", 1003);
List<Customer> customerList = (List<Customer>) query.getResultList();
然后,如果您对结果有疑问,则可以在JPA提供程序日志中查看已执行的SQL,从而可以更好地理解问题