簡體   English   中英

Spring Data Repository:傳遞給持久化的分離實體

[英]Spring Data Repository: Detached entity passed to persist

配置文件對象具有任務列表。 or ). 保存新配置文件時,任務列表也應與數據庫同步( )。 ). 問題是profile-repository的save() -method只允許一個或另一個方法依賴於屬性( )上面的級聯屬性集。

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-Test類

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屬性以避免異常。

@Transactional
@TransactionConfiguration
public class ProfileTaskRepositoryTest {
}

希望這可以幫助。

嘗試cascade = {CascadeType.PERSIST,CascadeType.MERGE}

Hibernate會話已過期;

使用

spring.datasource.removeAbandoned=false

要么

spring.datasource.removeAbandonedTimeout=...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM