我有以下四个表:
SCHEDULE_REQUEST TABLE: ID, APPLICATION_ID(FK)
APPLICATION TABLE: ID, CODE
USER_APPLICATION TABLE: APPLICATION_ID(FK), USER_ID(FK)
USER TABLE: ID, NAME
现在我想创建一个CriteriaBuilder
,其条件是为指定的用户ID选择ScheduleRequests
。
我有以下代码:
List<User> usersList = getSelectedUsers(); // userList contains users I wanted to select
CriteriaBuilder builder = getJpaTemplate().getEntityManagerFactory().getCriteriaBuilder();
CriteriaQuery<ScheduleRequest> criteria = builder.createQuery(ScheduleRequest.class);
Root<ScheduleRequest> scheduleRequest = criteria.from(ScheduleRequest.class);
criteria = criteria.select(scheduleRequest);
ParameterExpression<User> usersIdsParam = null;
if (usersList != null) {
usersIdsParam = builder.parameter(User.class);
params.add(builder.equal(scheduleRequest.get("application.userApplications.user"), usersIdsParam));
}
criteria = criteria.where(params.toArray(new Predicate[0]));
TypedQuery<ScheduleRequest> query = getJpaTemplate().getEntityManagerFactory().createEntityManager().createQuery(criteria);
// Compile Time Error here:
// The method setParameter(Parameter<T>, T) in the type TypedQuery<ScheduleRequest> is not
// applicable for the arguments (ParameterExpression<User>, List<User>)
query.setParameter(usersIdsParam, usersList);
return query.getResultList();
你能帮我解决一下如何将查询过滤器传递给关系对象吗? 我认为我在“application.userApplications.user”中所做的是错误的? 请真的需要帮助。
提前谢谢!
答案 0 :(得分:2)
使用规范的Metamodel和几个连接,它应该工作。如果您从以下伪代码(未测试)获得一些提示,请尝试:
...
Predicate predicate = cb.disjunction();
if (usersList != null) {
ListJoin<ScheduleRequest, Application> applications = scheduleRequest.join(ScheduleRequest_.applications);
ListJoin<Application, UserApplication> userApplications = applications.join(Application_.userApplications);
Join<UserApplication, User> user = userApplications.join(UserApplication_.userId);
for (String userName : usersList) {
predicate = builder.or(predicate, builder.equal(user.get(User_.name), userName));
}
}
criteria.where(predicate);
...
要了解Criteria Queries,请查看以下教程: http://www.ibm.com/developerworks/java/library/j-typesafejpa/ http://docs.oracle.com/javaee/6/tutorial/doc/gjitv.html
第二个链接还应该指导您如何使用Metamodel类,这些类应该由编译器/ IDE自动构建。