我一直在编写代码来构建条件查询以进行条件连接。但它并不正确。请考虑以下示例:
我有 2 个实体Owner
和Car
. Owner
与有OneToMany
关系Car
。
代码Owner
实体有List
s Car
。(@OneToMany
与 一起使用FetchType.LAZY
)
所有者.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;
...
}
汽车.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;
...
}
现在我的要求很简单,我想获得所有 TESLA 汽车的车主。以下代码适用于此:
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);
现在我的要求是,如果一个Owner
人拥有两辆汽车,一辆是特斯拉,另一辆是沃尔沃。我希望Owner
实体应该只包含TESLA
.
我怎么做?