解析多态子类属性jpa hibernate查询的条件

使用hibernate 3.6.10和hibernate jpa 2.0。

我的问题归结为需要在有点复杂的加入查询期间在子对象的列上设置一些条件。

我有一组对象类似于:

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Ball 
{
     private String name;
     //...getter and setter crud...
}


@Entity
public class BeachBall extend ball
{
    private boolean atTheBeach;
     //...getter and setter crud...

}

@Entity
public class SoccerBall extend ball
{
    private int numberOfKicks;
     //...getter and setter crud...
}

@Entity
public class Trunk 
{

    private Set<Ball> balls;


     @OneToMany(mappedBy = "trunk", cascade = CascadeType.ALL, orphanRemoval = true)
     public Set<Ball> getBalls()
     {
          return balls;
     }

}
@Entity
public class Car
{
    private Trunk trunk;
    private String carModel;

    //...getter and setter crud...
}

现在我需要查询有多少英式足球在具有特定模型的汽车中有20个踢球。

使用JPA我试图做一些事情:

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Car> criteriaQuery = criteriaBuilder.createQuery(Car.class);
    Root<Car> car= criteriaQuery.from(Car.class);
    Join<Car, Trunk> trunkJoin = car.join(Car_.trunk);
    Join<Trunk, Ball> ballJoin = trunkJoin.join(Trunk_.Balls);
    criteriaQuery.select(trunk);
    Predicate [] restrictions = new Predicate[]{  criteriaBuiler.equal(car.get(carModel), "Civic"), criteriaBuilder.equal(ballJoin.get("numberOfKicks"), 20)};
    criteriaQuery.where(restrictions);
    TypedQuery<Car> typedQuery = entityManager.createQuery(criteriaQuery);
    Car carWithSoccerBalls = typedQuery.getSingleResult();

在运行时,上面的代码会死掉,因为numberOfKicks只在英式足球上出现,并且由于它在Trunk中的输入方式只知道球。 如果我手动创建一个来自足球和设置标准来加入它,我可以查询numberOfKicks,但是我觉得必须有一种方法来通知查询该集合实际上是一个集合。

请注意我不能发布任何实际的代码,所以上面的例子都只是例子。

使用JPA和上面的hibernate有办法强制hibernate知道set <ball>实际上是否设置了<soccerball>?


由于时间限制,我正在采取简单的方法:(如果任何人都可以更好地回答,那么我有什么我会很乐意选择他们的答案在我的。

为了使标准API认识到我正在寻找继承表,我改变了我的查询代码:

   CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Car> criteriaQuery = criteriaBuilder.createQuery(Car.class);
    Root<Car> car= criteriaQuery.from(Car.class);
    Root<Soccerball> soccerballs = criteriaQuery.from(SoccerBall.class);
    Join<Car, Trunk> trunkJoin = car.join(Car_.trunk);
    Join<Trunk, Ball> ballJoin = trunkJoin.join(Trunk_.Balls);
    criteriaQuery.select(trunk);
    Predicate [] restrictions = new Predicate[]{  criteriaBuiler.equal(car.get(carModel), "Civic"), criteriaBuilder.equal(soccerball.get("numberOfKicks"),20), criteriaBuilder.equal(soccerball.get(SoccerBall_.id),car.get(Car_.id))};
    criteriaQuery.where(restrictions);
    TypedQuery<Car> typedQuery = entityManager.createQuery(criteriaQuery);
    Car carWithSoccerBalls = typedQuery.getSingleResult();
链接地址: http://www.djcxy.com/p/37081.html

上一篇: Resolving Criteria on Polymorphic child class attribute jpa hibernate query

下一篇: Hibernate Criteria many to many same object