-1

I have the classes Order, Article, Car

public class Order{
private List<Article> articles;
}

public abstract class Article{
private int id;
}

public class Car extends Article{
private String color;
}

public class Book extends Article{
private String title;
}

How can I check the articles that are a car using criteriaquery?

Dharman
  • 30,962
  • 25
  • 85
  • 135
user1345883
  • 451
  • 1
  • 8
  • 24

1 Answers1

0

Remember that queries are polymorphic.

CriteriaQuery<Order> q = cb.createQuery(Order.class);
Root<Order> order = q.from(Order.class);
Join<Order,Article> article = order.join("articles", JoinType.LEFT);
q.select(order)
.where(cb.equal(article.type(), Car.class));

You can restrict the type of the classes using type() and the subclass that you only want to retrieve.

In order to obtain color attribute, you must execute the TypedQuery and iterate over it.

TypedQuery<Order> qw = em.createQuery(q);
List<Order> orderList = qw.getResultList();

from orderList.get(index).getArticles().get(indexOfArticles).getColor();

In order to add a clause for the car color.

CriteriaQuery<Order> q = cb.createQuery(Order.class);
Root<Order> order = q.from(Order.class);
Join<Order,Car> article = order.join("articles", JoinType.LEFT);
q.select(order)
.where(cb.equal(article.get("color"), "red"),cb.equal(article.type(), Car.class));
Koitoer
  • 18,778
  • 7
  • 63
  • 86