이 게시물을 읽은 후 JPA map relation entity parentID이 코드를 적용하려고 시도했지만이 기능이 작동하지 않았습니다. JPA와 동일한 객체에 부모/자식 관계를 매핑하는 방법
이
내가 항상 실패@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);
}
시험이 줄을 실행
@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 updated parent category
assertEquals(1, sportCat.subCategories.size());
내 관계에 대한 설정에 따라 최대 절전 모드에서는 하위 범주를 검색 할 수 없으며 이유를 알 수 없습니다. 지금 나는 정말로 내 자신을 쏘지 않을 것이기 때문에 이것이 내 멍청한 것이 아니기를 바란다. (비록 늦어도 피곤할지라도). 그런데 코드에서 공용 변수를 신경 쓸 필요는 없지만 play! (playframework)를 사용하면 캡슐화가 처리됩니다. 사전에 도움을 주셔서 감사합니다
이것은 정확히 내가 한 일입니다. 상위 카테고리에 하위 카테고리를 추가하는 메소드를 추가했습니다. 나는 적절하게 시험을 수정했고 그것은 지금 내가 원하는만큼 정확하게 작동한다. 랄프 대단히 고마워. 그리고 그곳의 모든 사람들에게 감사합니다. – Alain