JPA / Hibernate:CriteriaBuilder - 如何使用关系对象创建查询?

问题描述 投票:3回答:1

我有以下四个表:

SCHEDULE_REQUEST表:ID,APPLICATION_ID(FK)

应用表: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”中所做的是错的?请真的需要帮助。

先感谢您!

java hibernate jpa filter criteria
1个回答
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自动构建。

© www.soinside.com 2019 - 2024. All rights reserved.