如何在JOIN中使用JPA Criteria API [英] How to use JPA Criteria API in JOIN

查看:127
本文介绍了如何在JOIN中使用JPA Criteria API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  • 我有五个表:公司,产品/服务,地址,国家和地区 城市.
  • 一个公司可以有n个产品的类别,1个地址和1个国家 地址实体内还有1个城市.
  • 用户选择了英格兰-利兹".
  • 我现在知道,我必须从db所在城市选择所有公司 是利兹,并用这些公司的产品填充产品/服务列表 产品或服务.之后,该用户可以选择例如牙医 从第三个列表开始.
  • 此后,我认识了Enlgand-Leeds-牙医,我必须填充 最后一张有补遗的清单(利兹的牙医)
  • I have five tables: Company, Product/Service, Address, Country and City.
  • A Company can have n products with category, 1 address with 1 country and 1 city inside the address entity.
  • A user has chosen "England - Leeds".
  • I know now that I have to select every companies from db where city is Leeds and populate product/service-list with those companies' products or services. After that user can select for instance dentist from the third list.
  • After that I know Enlgand - Leeds - Dentist and I have to populate the last list with compenies (dentists in Leeds)
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.)

我如何仅查询那些产品具有类别牙医的公司?

How can I query only those companies which have products with category dentist?

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,但是我不知道如何使用它.

Now I've got every company, how can I select only the companies with the correct category? I think I will need JOIN but how I don't know how to use it.

推荐答案

使用join(),

criteriaBuilder.equal(companyRoot.join("products").get("category"), "dentist")

看, http://en.wikibooks.org/wiki/Java_Persistence/Querying#Joining.2C_querying_on_a_OneToMany_relationship

这篇关于如何在JOIN中使用JPA Criteria API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆