I'm trying to update an object. As part of the process I load the old one from the database and "transfer" its property values to a new object.
But when I try to persist the new object I get the following error:
org.hibernate.PersistentObjectException: detached entity passed to persist: some.package.domain.Exercise
My entity looks as the following
@Entity
class Exercise(
val name: String,
val description: String,
@JsonIgnore
@ManyToOne
val creator: User,
@OneToMany(fetch = EAGER)
@Fetch(SUBSELECT)
val videos: MutableList<Video> = mutableListOf(),
@Id
@GeneratedValue(strategy = SEQUENCE)
val id: Long = 0
)
My code for persisting looks as the following
@Singleton
@Transactional
class ExerciseServiceDefault(override val repository: ExerciseRepository,
private val entityManager: EntityManager) : ExerciseService {
override fun update(id: Long, exercise: Exercise): Exercise {
val existing = get(id)
val new = Exercise(exercise.name, exercise.description, existing.creator, existing.videos, existing.pictures, id)
return repository.save(new)
// return entityManager.merge(new)
}
...
If I change the above code to use entityManager.merge(new)
everything works just fine. But I'd rather not have to inject the entityManager
.
Any clue about how I can make the updating happen using my repository
?
I've tried adding cascade = [MERGE]
to my relations to no avail.