小编典典

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

hibernate

我有以下四个表:

SCHEDULE_REQUEST表: ID,APPLICATION_ID(FK)

应用表: ID,代码

USER_APPLICATION表: APPLICATION_ID(FK),USER_ID(FK)

用户表: ID,NAME

现在,我想创建一个CriteriaBuilder条件条件,以便ScheduleRequests为指定的用户ID 选择。

我有以下代码:

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”中做的
是错误的吗?请真的需要帮助。

先感谢您!


阅读 541

收藏
2020-06-20

共1个答案

小编典典

使用规范的元模型和几个联接,它应该可以工作。尝试从以下伪代码中获得一些提示(未经测试):

...
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); 
...
为了理解“标准查询”,请看一下这些教程:http
//www.ibm.com/developerworks/java/library/j-typesafejpa/
http://docs.oracle.com/javaee/6/tutorial/
doc / gjitv.html

第二个链接还应指导您如何使用元模型类,该类应由编译器/ IDE自动构建。

2020-06-20