我有一个像这样自我映射的实体:
@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;
}
我想在父类别和子类别中按categoryName进行搜索。我使用criteriaBuilder。是否可以像这样进行搜索?我使用的第一个条件是仅在父类别中搜索以排除类别重复(父和子)。我使用条件:
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
我现在不知道如何进入子类别列表,如果在sabcategories中存在此值,我希望获得具有此子类别的父类别。
数据库设计:
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)
);
答案 0 :(得分:0)
对子类别和父
使用.join()How to use JPA Criteria API in JOIN
您可能必须为连接表定义别名,因为它具有相同的名称。
Hibernate Criteria Join with 3 Tables
Invalid alias when joining two JPA entities via JPA 2.0 CriteriaBuilder