Hibernate中的Criteria api查询不存在

时间:2012-12-06 20:56:41

标签: hibernate jpa criteria-api not-exists

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

我的数据库设置如下。

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();
}

2 个答案:

答案 0 :(得分:1)

您错过OneToOne实体中的反User关系:

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

请参阅this link,了解如何映射OneToOne关系。

此部分您有错误:subRootEntity.get("Route_.User")。这不是有效的语法,并且User实体中没有名为Route的属性:该属性名为driver(在阅读完最新编辑后)。

您可以使用以下两种方式获取Path表达式:

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

或使用Metamodel:

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

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

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

答案 1 :(得分:1)

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

为:

query.where(criteriaBuilder.not(criteriaBuilder.exists(subquery.select(subRootEntity))));