我有一个名为Category和CategorySet的表。
CREATE TABLE CATEGORY
(
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
category_name VARCHAR(40) NOT NULL,
description VARCHAR(255),
uuid VARCHAR(40)
);
CREATE TABLE CATEGORY_SET
(
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
parent INT NOT NULL,
child INT NOT NULL UNIQUE,
FOREIGN KEY (parent) REFERENCES CATEGORY (id),
FOREIGN KEY (child) REFERENCES CATEGORY (id)
);
Category.java
@Entity
@Table(name = "CATEGORY")
public class Category implements Serializable{
@Id
@Column(name = "ID")
@GeneratedValue
private Integer id;
@Column(name = "CATEGORY_NAME", nullable = false, length = 40)
private String name;
@Column(name = "DESCRIPTION", nullable = false, length = 255)
private String description;
@Column(name = "UUID", nullable = false, length = 40)
private String uuid;
@OneToMany(cascade = CascadeType.ALL)
@JoinTable(name = "CATEGORY_SET", joinColumns = {@JoinColumn(name = "PARENT")}, inverseJoinColumns = {@JoinColumn(name = "CHILD")})
private Collection<Category> subCategories = new LinkedHashSet<Category>();
public Category(String name, String description, String uuid, Collection<Category> categorySets) {
this.name = name;
this.description = description;
this.uuid = uuid;
this.categorySets = categorySets;
}
}
我希望获得所有根类别,这意味着它们不属于任何类别。
获取结果的SQL是:
SELECT DISTINCT CATEGORY.id
FROM CATEGORY
JOIN CATEGORY_SET
ON CATEGORY.id = CATEGORY_SET.parent
WHERE CATEGORY.id NOT IN (SELECT child
FROM CATEGORY_SET);
有人可以帮我写这个HQL。
答案 0 :(得分:1)
HQL查询是:
select c
from Category c
where c.id not in (select child from CategorySet)