0

我遇到了一个与自身相关的类的问题。对象是这样的:

类别.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]]

此外在插入中我控制一个类别只能是父母或孩子,一个类别不能是他自己的父亲。

4

1 回答 1

0

您使用同一列 ( categoryId) 来唯一标识一个类别,并引用父类别。这不可能奏效,因为所有类别显然都将自己作为父类别。您需要另一列来保存父类别 ID:

@Id
@SequenceGenerator(name = "CategoryIdGenerator", sequenceName = "CategorySeq")
@GeneratedValue(strategy = GenerationType.AUTO, generator = "CategoryIdGenerator")
@Column(name = "categoryId") // not necessary, but makes things clearer
public long getCategoryId() {
    return categoryId;
}

// optional must be true: some categories don't have a parent
@ManyToOne(optional = true, fetch = FetchType.EAGER) 
// insertable at least must be true if you want to create categories with a parent
@JoinColumn(name = "parentCategoryId", nullable = true)
public Category getParent() {
    return parent;
}
于 2012-08-10T20:09:37.777 回答