【发布时间】:2010-04-20 20:03:58
【问题描述】:
我对 SQL/HQL 非常不熟悉,目前被这个“可能”简单的问题所困扰:
我有两个多对多实体,有一个关系表:
汽车、汽车问题和问题。
一辆车可能有很多问题,
一个问题可能出现在许多汽车中,
CarProblem 是与其他属性的关联表。
现在,我想找到有指定问题的汽车,我该如何编写这样的 HQL? 所有 id 都是 Long 类型。
我尝试了很多 join / inner-join 组合,但都是徒劳的..
-- 更新:
对不起,忘了说:
汽车有很多问题
问题有很多 CarProblem
Car 和 Problem 在 Java Object 中没有直接连接。
--更新,下面的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!框架,所以这些属性都是公开的。
【问题讨论】: