我遇到了一个与自身相关的类的问题。对象是这样的:
类别.java
package com.borjabares.pan_ssh.model.category;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import com.borjabares.pan_ssh.util.Trimmer;
@Entity
public class Category {
private long categoryId;
private String name;
private Category parent;
public Category() {
}
public Category(String name, Category parent) {
this.name = name;
this.parent = parent;
}
@SequenceGenerator(name = "CategoryIdGenerator", sequenceName = "CategorySeq")
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "CategoryIdGenerator")
public long getCategoryId() {
return categoryId;
}
public void setCategoryId(long categoryId) {
this.categoryId = categoryId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = Trimmer.trim(name);
}
@ManyToOne(optional=false, fetch=FetchType.EAGER)
@JoinColumn(name="categoryId", insertable=false, updatable=false, nullable = true)
public Category getParent() {
return parent;
}
public void setParent(Category parent) {
this.parent = parent;
}
@Override
public String toString() {
return "Category [\ncategoryId=" + categoryId + ", \nname=" + name
+ ", \nparent=" + parent + "]";
}
}
协会只有一层深。插入和其他查询正在工作。但是当我尝试仅选择父类别或非父类别时,Hibernate 仅返回父类别或表的所有结果的 0 个结果。
现在的查询是这样的,但是我有很多其他带有连接的查询,为空,其他方法总是获得相同的结果。
@SuppressWarnings("unchecked")
public List<Category> listParentCategories() {
return getSession().createQuery(
"SELECT c FROM Category c WHERE c.parent is null ORDER BY c.name")
.list();
}
谢谢,对于我写这篇文章时可能犯的错误,我深表歉意。
编辑:
插入工作正常,当我列出 jUnit 中的所有类别并打印它们时,我得到了这个:
Category [
categoryId=416,
name=Deportes,
parent=null],
Category [
categoryId=417,
name=Formula 1,
parent=Category [
categoryId=416,
name=Deportes,
parent=null]],
Category [
categoryId=418,
name=F?tbol,
parent=Category [
categoryId=416,
name=Deportes,
parent=null]]
此外在插入中我控制一个类别只能是父母或孩子,一个类别不能是他自己的父亲。