I have an entity with self mapping like this:
@Entity
class Category{
String categoryName;
// other fields
@ManyToOne
@JoinColumn(name = "parent_category_id")
private Category parentCategory;
@OneToMany(mappedBy = "parentCategory", cascade = {CascadeType.All})
Set<Category> subcategories;
}
I want to search by categoryName in the parent category and in subcategories. I use criteriaBuilder. Is it posiible to make search like this? The first condition I use is search only in parent categories to exclude category duplication(parent and child). I use conditions:
Root root = ...
CriteriaBuilder cb = ...
Predicate predicate = cb.isNull(root.get("categoryName")); //after this search will be perfomed only by parent category
Predicate predicate = cb.like(cb.lower(root.get("categoryName")), "category value%"); //search perfomed only in parents
I don't now how to get into subcategories list and if in sabcategories this value is exist I want to get parent category with this subcategories.
Database design:
CREATE TABLE IF NOT EXISTS categories (
category_id BIGINT NOT NULL DEFAULT nextval('categories_category_id_seq'),
category_name VARCHAR(255) NOT NULL UNIQUE,
parent_category_id BIGINT,
CONSTRAINT categories_pkey PRIMARY KEY (category_id),
CONSTRAINT parent_category_id_fk FOREIGN KEY (parent_category_id) REFERENCES
categories (category_id)
);