一尘不染

我如何使用JPA在同一对象上映射父/子关系

hibernate

阅读了这篇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),它负责封装。预先感谢您的任何帮助


阅读 327

收藏
2020-06-20

共1个答案

一尘不染

将父级和子级映射到同一类不是问题。-问题是您需要手工维护双向关系的两端。

child.setParent(parent)
parent.addChild(child)

顺便说一句:仅在一侧(负责将关系存储在数据库中)设置,存储和重新加载实体在某些情况下也会起作用。(而且您会在许多旧教程中找到这个肮脏的把戏)。但是我认为这是不好的做法。(在您的测试用例中,在保存子项之后,需要在重新加载父项之前清理缓存。)

2020-06-20