Issue
I have a Spring-MVC
online-store project where I use Spring Boot
and Hibernate
. I decided to use the Specification
for filtering. Thus, I wrote a method for the specification using JOINS. Please, tell me how you can write the same method without JOIN.
TeaSpecification class:
public static Specification<Tea> getTeasByFilter(Long colorId, Long typeId, Long countryId) {
return (root, query, criteriaBuilder) -> {
Join<Object, Object> colorJoin = root.join(Tea_.TEA_COLOR);
Join<Object, Object> typeJoin = root.join(Tea_.TEA_TYPE);
Join<Object, Object> countryJoin = root.join(Tea_.COUNTRIES);
Predicate countryPredicate = criteriaBuilder.equal(countryJoin.get(Countries_.ID), countryId);
Predicate colorPredicate = criteriaBuilder.equal(colorJoin.get(TeaColor_.ID), colorId);
Predicate typePredicate = criteriaBuilder.equal(typeJoin.get(TeaColor_.ID), typeId);
return criteriaBuilder.and(colorPredicate, typePredicate, countryPredicate);
};
}
Drink class(Tea extends Drink):
@Inheritance(strategy = InheritanceType.JOINED)
public class Drink {
// Fields
//
private @Id
@GeneratedValue
Long id;
private String name;
private BigDecimal price;
private String about;
@Column(name = "is_deleted")
private boolean isDeleted;
// Relationships
//
@ManyToOne
@JoinColumn(name = "packaging_id")
private Packaging packaging;
@ManyToOne
@JoinColumn(name = "manufacturer_id")
private Manufacturer manufacturer;
@ManyToOne
@JoinColumn(name = "country_id")
private Countries countries;
}
public class Tea extends Drink {
// Relationships
//
@ManyToOne
@JoinColumn(name = "type_id")
private TeaType teaType;
@ManyToOne
@JoinColumn(name = "color_id")
private TeaColor teaColor;
}
Solution
public class TeaSpecification {
public static Specification<Tea> getTeasByFilter(Long colorId, Long typeId, Long countryId) {
return (root, query, criteriaBuilder) -> {
Predicate colorPredicate = criteriaBuilder
.equal(root.get(Tea_.teaColor).get(TeaColor_.id), colorId);
Predicate typePredicate = criteriaBuilder
.equal(root.get(Tea_.teaType).get(TeaType_.id), typeId);
Predicate countryPredicate = criteriaBuilder
.equal(root.get(Tea_.countries).get(Countries_.id), countryId);
return criteriaBuilder.and(colorPredicate, typePredicate, countryPredicate);
};
}
}
Answered By - Artur Vartanyan