views:

248

answers:

2

I am very unfamiliar with SQL/HQL , and am currently stuck with this 'maybe' simple problem :

I have two many-to-many Entities , with a relation table :

Car , CarProblem , and Problem .

One Car may have many Problems ,

One Problem may appear in many Cars,

CarProblem is the association table with other properties .

Now , I want to find Car(s) with specified Problem , how do I write such HQL ? All ids are Long type .

I've tried a lot of join / inner-join combinations , but all in vain..

-- updated :

Sorry , forget to mention :

Car has many CarProblem

Problem has many CarProblem

Car and Problem are not directly connected in Java Object.

-- update , java code below --

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

The Model is from Play! framework , so these properties are all public .

A: 

Assuming everything is already mapped correctly:

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

serg
sorry , I forget to mention that Car is not directly link to Problem.Car has many CarProblems.Problem has many CarProblems.
smallufo
Can you please provide your mapping? You have two one-to-many relations?
serg
Thank you , I've append my code in my question. It is used in Play! framework . I want to use one line of HQL in Problem.findCars()...
smallufo
A: 

I would question the need for the CarProblem altogether, but if you are going to keep this mapping I believe you could do something like this:

select c from CarProblem as cp join cp.car as c join cp.problem as p where p.id = :id
digitaljoel
Thank you , it works !!!BTW , The reason why I keep a CarProblem entity is there are other properties here.
smallufo
yeah, I saw the "...other properties" and I figure your mapping is your business, so I left that alone... mostly :)
digitaljoel