Is it somehow possible to create a criteria query that performs an outer join on another entity if that entity is not mapped?
I know that an inner join is possible when you do a cross join and add the join condition manually. It would look like this:
CriteriaBuilder cb = getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
Root<Car> car = cq.from(Car.class);
Root<Color> color = cq.from(Ccolor.class);
cq.where(cb.equal(car.get("colorUuid"), color.get("uuid")));
However I need the behaviour of an outer join in my case.
So let's say I have these entities:
class Car {
@Column(name="color_uuid")
private String colorUuid;
}
class Color {
private String uuid;
private String name;
}
Lets say Color is optional and that's why I need an outer join. The SQL would look like
SELECT * from car LEFT OUTER JOIN color ON car.color_uuid = color.uuid;
Can I do this with Criteria?
I suggest you change the classes in order to have a relationship that logically already exists.
class Car {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "color_uuid", referencedColumnName = "uuid")
private Color color;
}
class Color {
private String uuid;
private String name;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "color")
private List<Car> cars;
}
Then you can build the left join using criteria:
CriteriaQuery<Car> criteriaQuery = criteriaBuilder.createQuery(Car.class);
Root<Car> root = criteriaQuery.from(Car.class);
root.join("color", JoinType.LEFT);
List<Car> cars = em.createQuery(criteriaQuery).getResultList();
You can't do this with criteria api, I've faced the same problem as you. Also a cross join can't help. What I can suggest is:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.