public class Company implements java.io.Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Short companyId;
@OneToOne(cascade=CascadeType.PERSIST)
private Address address;
private String companyName;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "company",cascade=CascadeType.PERSIST)
private Set<Product> products = new HashSet<Product>(0);
public class Product implements java.io.Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "productId", unique = true, nullable = false)
private Integer productId;
private Short branchId;
private String productName;
private String sku;
private String category; ------> I am using this field in company search (dentists, garages etc.)
我如何只查询那些拥有牙科类别产品的公司?
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<Company> criteria = criteriaBuilder.createQuery( Company.class );
Root<Company> companyRoot = criteria.from( Company.class );
//criteria.select(companyRoot);
TypedQuery<Company> q = em.createQuery(criteria);
List<Company> results = q.getResultList();
现在我有了每家公司,我怎样才能选择具有正确类别的公司?我想我需要JOIN
,但我不知道如何使用它。
答案 0 :(得分:21)
使用join(),
criteriaBuilder.equal(companyRoot.join("products").get("category"), "dentist")