Reputation: 2674
A profile object has a list of tasks. When saving a new profile, the list of tasks should be also synchronized with Database (inserted or updated). The problem is the profile-repository's save()-method allows only the one or the other method depends on the cascade property set above the attribute (CascadeType.PERSIST or MERGE).
The Profile class
@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 class
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
}
I suppose the questionTask-object becomes detached when taskRepo saves it in DB and then closes the 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
...
The profileRepo.save() should be able to handle both insertion and update of list of tasks. Is there a elegant way to solve this problem?
Upvotes: 4
Views: 5203
Reputation: 1353
Hibernate session has expired;
Use
spring.datasource.removeAbandoned=false
or
spring.datasource.removeAbandonedTimeout=...
Upvotes: 0
Reputation: 2668
You should put @Transactional
attributes on the test class to avoid the exception.
@Transactional
@TransactionConfiguration
public class ProfileTaskRepositoryTest {
}
Hope this helps.
Upvotes: 2