Reputation: 573
I have 2 classes. The first class Car has a list of passengers. I need a Hibernate Criteria that will return the Car for which I have a single passenger. So something like this
class Car {
@Id
private Long id;
@OneToMany
private List<Passenger> passengers;
}
And in the Hibernate class
@Override
public Car retrieve(Passenger passenger) {
Criteria criteria = super.createCriteria();
criteria.add(Restrictions.eq("passengers", passenger));
return (Car ) criteria.uniqueResult();
}
However the below wont really work. So any suggestions how to do this
Upvotes: 1
Views: 2091
Reputation: 873
You need to join the Car table with the Passenger table here, which can be done with criteria API's aliases. you should try the following:
@Override
public Car retrieve(Passenger passenger) {
Criteria criteria = super.createCriteria();
criteria.createAlias("passengers", "p");
criteria.add(Restrictions.eq("p.id", passenger.getId()));
return (Car) criteria.uniqueResult();
}
Another tip: I think that a passenger can only appear once in a car, so I would prefer Set<Passenger>
instead of List<Passenger>
.
Upvotes: 2