I’m having a trouble with a class that’s associated with itself. The object it’s this:
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 + "]";
}
}
The association it’s only one level deep. Insert, and other queries are working. But when I try to select only parent categories or non parent categories Hibernate only returns 0 results for parent categories or all the results of the table.
The queries, as they are right now is like this, but I’ve a lot of other queries with joins, is null and other methods obtaining always the same result.
@SuppressWarnings("unchecked")
public List<Category> listParentCategories() {
return getSession().createQuery(
"SELECT c FROM Category c WHERE c.parent is null ORDER BY c.name")
.list();
}
Thank you, and sorry for the mistakes I’ve maybe made writing this.
EDIT:
Insertion works fine, when I list all the categories in jUnit and print them I’ve got this:
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]]
Besides in the insertion I’m controlling that a category can only be parent or child, and a category can’t be his own father.
You’re using the same column (
categoryId) to uniquely identify a category, and to reference the parent category. This can’t possibly work, since all categories would obviously have themselves as parent. You need another column to hold the parent category ID: