I have been working on a code to build a Criteria Query to do a conditional join. But its not quit correct. Please consider following example:
I have 2 Entities Owner
and Car
. Owner
has OneToMany
relation with Car
.
On code Owner
entity has List
of Car
s.(Using @OneToMany
with FetchType.LAZY
)
Owner.java:
@Entity
public class Owner {
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE)
private int id;
private String name;
private String email;
@OneToMany(mappedBy="owner",fetch=FetchType.LAZY)
private List<Car> cars;
...
}
Car.java
@Entity
public class Car{
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private int id;
private String manufacturer;
private String regnumber;
@ManyToOne
@JoinColumn(name="ownerid")
private Owner owner;
...
}
Now my requirement is simple I want to get all the Owners of TESLA cars. Following code works good for that:
CriteriaQuery<Owner> cq = cb.createQuery(Owner.class);
Root<Owner> rootowner = cq.from(Owner.class);
rootowner.fetch("cars");
cq.distinct(true);
Join<Owner, Car> carjoin= rootowner.join(Owner_.cars);
Expression<String> carmanExp = carjoin.get(Car_.manufacturer);
Predicate p = cb.like(carmanExp, "TESLA");
cq.where(p);
TypedQuery<Owner> tq = em.createQuery(cq);
Now my requirement is, if a Owner
owns 2 cars, one is TESLA and another is VOLVO. I want Owner
entity should contain only TESLA
.
How do I do that?