2

我正在尝试更新一个对象。作为该过程的一部分,我从数据库中加载旧的并将其属性值“传输”到新对象。

但是,当我尝试保留新对象时,出现以下错误:

org.hibernate.PersistentObjectException: detached entity passed to persist: some.package.domain.Exercise

我的实体如下所示

@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
)

我的持久化代码如下所示

@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)
    }
...

如果我更改上面的代码以使用entityManager.merge(new)一切正常。但我宁愿不必注入entityManager.

关于如何使用 my 进行更新的任何线索repository

我试过增加cascade = [MERGE]我的关系无济于事。

4

0 回答 0