Spring Data Repository: 传递给持久化的实体已脱离上下文

4

一个profile对象有一个任务列表。当保存一个新的profile时,任务列表也应该与数据库同步(插入更新)。问题是profile-repository的save()方法只允许一种方法,具体取决于属性上方设置的cascade属性(CascadeType.PERSIST或MERGE).

Profile类

@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将questionTask对象保存在数据库中并关闭会话时,它就变成了分离状态。
异常:
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() 应该能够处理任务列表的插入更新。有没有一种优雅的方式来解决这个问题?


什么是“Task”?它是你设计的类吗?你能贴出那段代码吗? - gaganbm
3个回答

2

为避免异常,您应该在测试类上放置@Transactional属性。

@Transactional
@TransactionConfiguration
public class ProfileTaskRepositoryTest {
}

希望这可以帮助到您。

这不是测试类所需的。它应该添加在实际扩展JpaRepository的TaskRepository中。 - gaganbm
1
问题描述中提到,ProfileRepository和TaskRepository扩展自接口JpaRepository。如果CreateProfileWithExistingTask是一个服务类方法,那么@Transactional属性应该放在服务类上,而不需要将其放在测试类中,除非您有在事务中运行测试的要求。 - Nitin Arora

0

Hibernate会话已过期;

请使用:

spring.datasource.removeAbandoned=false

或者

spring.datasource.removeAbandonedTimeout=...

0

尝试级联 = { CascadeType.PERSIST, CascadeType.MERGE }


1
恐怕它会抛出相同的异常。 - kk-dev11

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接