프로필 개체는 작업 목록을 가지고 있습니다. 새 프로필을 저장할 때 작업 목록도 데이터베이스 ( 삽입 된 또는 )와 동기화되어야합니다. 문제는 profile-repository의 save()입니다. -method는 하나 또는 다른 메소드 만이 속성 ( CascadeType.PERSIST 또는 MERGE) 위에 설정된 캐스케이드 속성에 따라 달라질 수 있습니다.스프링 데이터 저장소 : 분리 된 엔터티가 전달되어 전달됨
프로파일 클래스
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public abstract class AbstractProfile implements Profile {
...
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
private List<Task> tasks;
..
의 JUnit 테스트 클래스
public class ProfileTaskRepositoryTest {
@Autowired
private ProfileRepository profileRepo; //extends JpaRepository
@Autowired
private TaskRepository taskRepo; //extends JpaRepository
@Test // ->this test passes
public void testCreateProfileWithNewTask() {
//profileData and taskData hold dummy data. They return new objects
AbstractProfile interview = profileData.createITInterviewProfile();
Task questionTask = taskData.createInterviewQuestionTask();
//add new task to profile and save
interview.addTask(questionTask);
profileRepo.save(interview);
//task repository confirms the insertion
assertTrue(taskRepo.count() == 1);
}
@Test // ->this test fails
public void testCreateProfileWithExistingTask() {
//first create task and save in DB
Task questionTask = taskData.createInterviewQuestionTask(); // transient obj
taskRepo.save(questionTask); // questionTask becomes detached
// then create a new profile and add the existing task.
// the problem is the existing task is now detached)
AbstractProfile interview = profileData.createITInterviewProfile();
interview.addTask(questionTask);
profileRepo.save(interview); // !!! this throws an exception
}
나는 taskRepo가 세션을 종료 한 후 DB에 저장하고 때 questionTask -object가 분리된다 같아요.
예외 :
org.springframework.orm.jpa.JpaSystemException: org.hibernate.PersistentObjectException: detached entity passed to persist: *.Task; nested exception is javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: *.Task
...
profileRepo.save는()는 작업 목록의 두 삽입 및 갱신을 처리 할 수 있어야합니다. 이 문제를 해결할 수있는 우아한 방법이 있습니까? 당신은 예외를 피하기 위해 테스트 클래스에 @Transactional
속성을 넣어해야
? 그것은 당신이 디자인 한 수업입니까? 그 코드를 게시 할 수 있습니까? – gaganbm