3

我正在尝试编写查询,它返回未分配给路线的驱动程序列表。

我的数据库设置如下。

Route:
route_id
user_id//specified as driver

User:
user_id
role // need to select user, which is Driver role

只有路线看到用户(司机),用户(司机)看不到路线。

这是我尝试编写这样的查询。

public List<User> getUnsignedDrivers(){
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();

    CriteriaQuery<User> query = criteriaBuilder.createQuery(User.class);
    Root<User> user = query.from(User.class);
    query.select(user);

    Subquery<Route> subquery = query.subquery(Route.class);
    Root<Route> subRootEntity = subquery.from(Route.class);
    Predicate correlatePredicate = criteriaBuilder.equal(subRootEntity.get("Route_.User"), user);
    subquery.where(correlatePredicate);
    query.where(criteriaBuilder.not(criteriaBuilder.exists(subquery)));

    TypedQuery<User> typedQuery = entityManager.createQuery(query);
    return typedQuery.getResultList();
}

我是 jpa 的新手,所以这就是问题所在。

更具体地说,我需要选择具有角色驱动程序的用户,这些用户未设置为任何路线

我的实体设置如下:

    @Entity
public class Route {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

@OneToOne(fetch = FetchType.EAGER, cascade = {})
@JoinColumn(name = "user_id", nullable = true)
private User driver;
.....
@Entity
public class User {

public static enum Role {
    ADMIN, MANAGER, DRIVER;
}

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@Enumerated(EnumType.STRING)
@Column(nullable = false)
private Role role;

更新:当前查询

CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();

    CriteriaQuery<User> query = criteriaBuilder.createQuery(User.class);
    Root<User> user = query.from(User.class);
    Predicate predicateRole = criteriaBuilder.equal(user.get("role"), User.Role.DRIVER);
    query.where(predicateRole);
    query.select(user);


    Subquery<Route> subquery = query.subquery(Route.class);
    Root<Route> subRootEntity = subquery.from(Route.class);
    Predicate correlatePredicate = criteriaBuilder.equal(subRootEntity.get("driver"), user);
    subquery.where(correlatePredicate);
    query.where(criteriaBuilder.not(criteriaBuilder.exists(subquery)));

    TypedQuery<User> typedQuery = entityManager.createQuery(query);
    return typedQuery.getResultList();

问题依然存在

我得到这个例外:

java.lang.IllegalStateException: No explicit selection and an implicit one cold not be determined
at org.hibernate.ejb.criteria.QueryStructure.locateImplicitSelection(QueryStructure.java:296)
at org.hibernate.ejb.criteria.QueryStructure.render(QueryStructure.java:249)
at org.hibernate.ejb.criteria.CriteriaSubqueryImpl.render(CriteriaSubqueryImpl.java:282)
at org.hibernate.ejb.criteria.predicate.ExistsPredicate.render(ExistsPredicate.java:58)
at org.hibernate.ejb.criteria.QueryStructure.render(QueryStructure.java:258)
at org.hibernate.ejb.criteria.CriteriaQueryImpl.render(CriteriaQueryImpl.java:340)
at org.hibernate.ejb.criteria.CriteriaQueryCompiler.compile(CriteriaQueryCompiler.java:217)
at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:587)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240)
at $Proxy25.createQuery(Unknown Source)

扔在这条线上TypedQuery<User> typedQuery = entityManager.createQuery(query);

解决 这个问题对我来说非常有效。我写了这个,因为我不能使用反向关系。

public List<User> getUnsignedDrivers(){
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();

    CriteriaQuery<User> query = criteriaBuilder.createQuery(User.class);
    Root<User> user = query.from(User.class);
    Predicate predicateRole = criteriaBuilder.equal(user.get("role"), User.Role.DRIVER);
    query.where(predicateRole);
    query.select(user);

    TypedQuery<User> typedQuery = entityManager.createQuery(query);
    List<User> allDrivers = typedQuery.getResultList();
    List<User> notAssignedDrivers = new ArrayList<User>();
    List<Route> haveDriverRoutes = getRouteWithNoDrives();
    for (User driver : allDrivers){
        if (!isDriverAssigned(haveDriverRoutes,driver.getId())){
            notAssignedDrivers.add(driver);
        }
    }
    return notAssignedDrivers;
}

private boolean isDriverAssigned(List<Route> haveDriverRoutes, long driverId){
    for(Route route : haveDriverRoutes){
        if (route.getDriver().getId() == driverId){
            return true;
        }
    }
    return false;
}

@SuppressWarnings("unchecked")
public List<Route> getRouteWithNoDrives() {
    Query query = entityManager.createQuery("SELECT o FROM " + type.getSimpleName() + " o WHERE o.driver != null");
    return  query.getResultList();
}
4

2 回答 2

1

您缺少实体中的反向OneToOne关系:User

@OneToOne(mappedBy="driver")
private Route route;

有关如何映射 OneToOne 关系的信息,请参阅此链接。

你在这部分有一个错误:subRootEntity.get("Route_.User"). 这不是一个有效的语法,并且您没有UserRoute实体中调用的属性:该属性被调用driver(在阅读了您的最新编辑之后)。

您有 2 种方法来获取该Path表达式,或者使用:

Path<User> path = subRootEntity.get("driver");
// in a compact way: 
Predicate correlatePredicate = criteriaBuilder.equal(subRootEntity.get("driver"), user);

或通过使用元模型:

Path<User> path = subRootEntity.get(Route_.driver);
// in a compact way: 
Predicate correlatePredicate = criteriaBuilder.equal(subRootEntity.get(Route_.driver), user);

你似乎混合了这两种方法。有关使用 Metamodel 的更多信息,请参阅本文

查询的其余部分看起来是正确的。

于 2012-12-07T09:10:02.587 回答
1

添加子查询的行应该返回一些东西。所以你应该改变: query.where(criteriaBuilder.not(criteriaBuilder.exists(subquery)));

到:

query.where(criteriaBuilder.not(criteriaBuilder.exists(subquery.select(subRootEntity))));
于 2014-01-07T19:09:17.150 回答