具有反身关联的HQL不起作用

时间:2012-08-10 19:03:14

标签: java spring hibernate junit

我遇到了与自己相关的课程。对象就是这样:

Category.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结果或表格的所有结果。

现在的查询是这样的,但是我有很多其他的连接查询,是null,其他方法总是得到相同的结果。

@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]]

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

1 个答案:

答案 0 :(得分: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;
}