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();
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.
Advertisements. The Criteria API is a predefined API used to define queries for entities. It is the alternative way of defining a JPQL query. These queries are type-safe, and portable and easy to modify by changing the syntax.
Criteria in Hibernate can be used for join queries by joining multiple tables, useful methods for Hibernate criteria join are createAlias(), setFetchMode() and setProjection() Criteria in Hibernate API can be used for fetching results with conditions, useful methods are add() where we can add Restrictions.
use join(),
criteriaBuilder.equal(companyRoot.join("products").get("category"), "dentist")
See, http://en.wikibooks.org/wiki/Java_Persistence/Querying#Joining.2C_querying_on_a_OneToMany_relationship
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With