阅读这篇文章JPA 映射关系实体 parentID后,我尝试将其应用于我的代码,但这对我不起作用。
这是我的对象中的代码
@Entity
public class Category extends Model {
public static final int EASY = 1;
public static final int MEDIUM = 2;
public static final int HARD = 3;
public static final int VERRY_HARD = 4;
public String name;
public String fullName;
public boolean active;
public Date createdOn;
public int difficulty;
@ManyToOne
@JoinColumn(name = "FK_PARENT_CATEGORY")
public Category parentCategory;
@OneToMany(mappedBy="parentCategory", cascade = CascadeType.ALL)
public List<Category> subCategories;
public Category(Category parentCategory, String name, boolean active) {
this.name = name;
this.active = active;
this.parentCategory = parentCategory;
this.subCategories = new ArrayList<Category>();
this.createdOn = new Date();
this.difficulty = Category.EASY;
this.fullName = name;
if (parentCategory != null)
this.fullName = parentCategory.fullName + "/" + this.fullName;
}
现在这是我运行的测试
@Test
public void testParentAndSubCategories() {
//Create the parent category
new Category(null, "Sport", true).save();
Category sportCat = Category.find("byName", "Sport").first();
//Test the newly created parent category state
assertNotNull(sportCat);
assertEquals("Sport", sportCat.name);
assertEquals(true, sportCat.active);
assertEquals("Sport", sportCat.fullName);
assertNull(sportCat.parentCategory);
assertEquals(0, sportCat.subCategories.size());
//Create the subCategory
new Category(sportCat, "Hockey", false).save();
Category hockeyCat = Category.find("byName", "Hockey").first();
// Test the newly created sub category
assertNotNull(hockeyCat);
assertEquals("Hockey", hockeyCat.name);
assertEquals(false, hockeyCat.active);
assertEquals("Sport/Hockey", hockeyCat.fullName);
assertNotNull(hockeyCat.parentCategory);
assertEquals("Sport", hockeyCat.parentCategory.name);
assertEquals(0, sportCat.subCategories.size());
//Fetch new values for parent category
sportCat = Category.find("byName", "Sport").first();
// Test updated parent category
assertEquals(1, sportCat.subCategories.size());
assertEquals("Hockey", sportCat.subCategories.get(0).name);
}
这行测试总是失败。
// Test updated parent category
assertEquals(1, sportCat.subCategories.size());
根据我的关系设置,Hibernate 无法检索子类别,我不知道为什么。现在我真的很希望这不是我的愚蠢,因为我要自己开枪(即使已经很晚了,我很累)。顺便说一句,不要介意代码中的公共变量,我使用的是 play!(playframework),它负责封装。提前感谢您的帮助