I have a problem using Hibernate.
I want to do something no really sophisticated and I can't find a way to do it.
I have this DB schema:
[vehicle]<=>[company_vehicle]<=>[company]
And I have those entities :
One abstract entity
Vehicle :
Code:
@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="Vehicle_type",discriminatorType=DiscriminatorType.STRING)
@Table(name="Vehicle")
public abstract class Vehicle {
[...]
}
2 Enities which inherit form Vehicle class.
The
Car entity:
Code:
@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(discriminatorType=DiscriminatorType.STRING)
@DiscriminatorValue("car")
public class Car extends Vehicle {
@ManyToMany
@JoinTable(
name="company_vehicle",
joinColumns=@JoinColumn(name="vehicle_id",referencedColumnName="vehicle_id"),
inverseJoinColumns=@JoinColumn(name="company_id",referencedColumnName="company_id")
)
private Collection<Company> companies;
}
and the
Truck entity:
Code:
@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(discriminatorType=DiscriminatorType.STRING)
@DiscriminatorValue("truck")
public class Truck extends Vehicle {
@ManyToMany
@JoinTable(
name="company_vehicle",
joinColumns=@JoinColumn(name="vehicle_id",referencedColumnName="vehicle_id"),
inverseJoinColumns=@JoinColumn(name="company_id",referencedColumnName="company_id")
)
private Collection<Companies> companies;
}
and finally, one other entity
Company which have 2 ManyToMany relationships with 2 entities :
Code:
@Entity
@Table(name="company")
public class Company {
[...]
@ManyToMany(mappedBy="companies")
private Collection<Car> cars;
@ManyToMany(mappedBy="companies")
private Collection<Truck> trucks;
}
The problem is that Hibernate give me all vehicles when I only ask for the cars.
For example, if I have 2 cars and 1 truck for a company, I get 3 cars.
Basically, Hibernate give me the result of:
Code:
SELECT vehicle.id
FROM vehicle,company_vehicle
WHERE vehicle.id=company_vehicle.id_vehicle
AND company_vehicle.id_company=X
and I want that:
Code:
SELECT vehicle.id
FROM vehicle,company_vehicle
WHERE vehicle.id=company_vehicle.id_vehicle
AND company_vehicle.id_company=X
AND vehicle.type="car"
Thank you for your help.