0

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)
);
Yurii Kozachok
  • 615
  • 1
  • 7
  • 21

1 Answers1

0

Use .join() for the subCategories and the parent

How to use JPA Criteria API in JOIN

You may have to define an alias for the joined table, because the do have the same names.

Hibernate Criteria Join with 3 Tables

Invalid alias when joining two JPA entities via JPA 2.0 CriteriaBuilder

Pwnstar
  • 2,333
  • 2
  • 29
  • 52