[英]JPA Criteria Builder with join and dynamic parameters
I have 2 classes with One-to-Many relationship.我有 2 个具有一对多关系的课程。 Customer (class) has many Transactions (class)
客户(类)有很多交易(类)
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();
I have 2 data from the DB: Customer Table我有来自数据库的 2 个数据:客户表
ClientId | Name |
1 | James |
2 | Eli |
Transactions Table:交易表:
ClientId | Status Type| Amount| TransactionId |
1 | 1002 | 100 | 1 |
1 | 1003 | 200 | 2 |
I need to make my query above to accept multiple parameters (dynamic).我需要在上面进行查询以接受多个参数(动态)。 These parameters will be coming from the Customer's attributes such as name, some parameters will be coming from the Transactions class.
这些参数将来自客户的属性,例如名称,一些参数将来自交易类。 However, when I tried to execute my code above it always get the 1st record (1002) in my database which is incorrect.
但是,当我尝试执行上面的代码时,它总是在我的数据库中获得第一条记录 (1002),这是不正确的。
Please give me somelight.请给我一点。 Questions:
问题:
You are currently just passing in a Literal.您目前只是传入一个文字。 This is not the same as a Parameter.
这与参数不同。 See http://www.datanucleus.org:15080/products/accessplatform_5_2/jpa/query.html#_criteria_api_parameters
请参阅http://www.datanucleus.org:15080/products/accessplatform_5_2/jpa/query.html#_criteria_api_parameters
Change your code to将您的代码更改为
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();
Then if you get a problem with the result, you look in the JPA providers log at the SQL that was executed, and can understand the problem better然后,如果结果出现问题,您可以查看 JPA 提供程序日志中执行的 SQL,并且可以更好地理解问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.