Hibernate HQL m:n加入问题

时间:2010-04-20 20:03:59

标签: hibernate join hql

我对SQL / HQL非常不熟悉,目前我仍然坚持这个“可能”的简单问题:

我有两个多对多实体,有一个关系表:

汽车,汽车问题和问题。

一辆车可能有很多问题,

许多汽车可能会出现一个问题,

CarProblem是与其他属性的关联表。

现在,我想找到具有指定问题的Car,我该如何编写这样的HQL? 所有ID都是Long类型。

我尝试了很多连接/内连接组合,但都是徒劳的..

- 更新:

抱歉,别忘了:

汽车有很多CarProblem

问题有很多CarProblem

在Java对象中没有直接连接Car和Problem。

- 更新,下面的java代码 -

@Entity
public class Car extends Model{
  @OneToMany(mappedBy="car" , cascade=CascadeType.ALL)
  public Set<CarProblem> carProblems;
}

@Entity
public class CarProblem extends Model{
  @ManyToOne
  public Car car;      
  @ManyToOne
  public Problem problem;    
  ... other properties
}


@Entity
public class Problem extends Model  {
  other properties ...
  // not link to CarProblem , It seems not related to this problem

  // **This is a very stupid query , I want to get rid of it ...**
  public List<Car> findCars()
  {
    List<CarProblem> list = CarProblem.find("from CarProblem as cp where cp.problem.id = ? ", id).fetch();
    Set<Car> result = new HashSet<Car>();
    for(CarProblem cp : list)
      result.add(cp.car);

    return new ArrayList<Car>(result);
  }
}

模特来自Play!框架,所以这些属性都是公开的。

2 个答案:

答案 0 :(得分:2)

我会完全质疑CarProblem的必要性,但是如果你要保留这个映射,我相信你可以这样做:

select c from CarProblem as cp join cp.car as c join cp.problem as p where p.id = :id

答案 1 :(得分:0)

假设所有内容都已正确映射:

from Car c join c.problems p where p.id = :id

相关问题