java - Spring 数据存储库 : Detached entity passed to persist

标签 java spring hibernate jpa spring-data-jpa

配置文件对象有一个任务列表。 保存新配置文件时,任务列表也应与数据库同步(插入更新)。问题是 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
    }

我假设 questionTask-object 在 taskRepo 将它保存在 DB 中然后关闭 session 时分离。

异常(exception):

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 属性以避免异常。

@Transactional
@TransactionConfiguration
public class ProfileTaskRepositoryTest {
}

希望这对您有所帮助。

关于java - Spring 数据存储库 : Detached entity passed to persist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27531800/

相关文章:

java - 防止违反 Hibernate 的 UNIQUE 约束

java - 我正在尝试以垂直模式从左上角到右下角搜索我的java多维数组。我的代码有什么问题?

java - 多个重复的子元素 xml

java - 从 java 1.4、EJB 1 迁移到 Java 6 和 EJB 3

java - 为什么Spring IOC中工厂bean需要非静态方法

java - 使用 c3p0 时 MySQL Hibernate 连接问题

java - 初始化泛型类型的 Java 泛型数组

java - 有什么办法可以让这个java调用变小吗?

java - 如何使用 Spring Boot 2+ 更改 jasper 报告 PDF 的标题和图标?

hibernate - hibernate 投影列表