编程语言
首页 > 编程语言> > java – 多态子类属性jpa hibernate查询的解析标准

java – 多态子类属性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仅在soccerball上而死,并且由于它在Trunk中输入的方式,它只知道球.如果我手动创建一个从足球和设置标准加入它我可以查询numberOfKicks,但我觉得必须有一种方法来通知查询该集实际上是一个集.

请注意我无法发布任何实际代码,因此以上所有示例都只是示例.

像上面那样使用JPA和hibernate有一种方法可以强制hibernate知道set<球>实际上是设置<足球>?

解决方法:

由于时间的限制,我正在采取简单的方法:(.如果有人能够更好地回答那么我有什么我会很乐意选择他们的答案超过我的.

为了使条件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();

标签:java,jpa,hibernate,criteria-api
来源: https://codeday.me/bug/20190624/1282389.html