Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/hibernate/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Hibernate 测试中带有@MapsId注释的子实体中的PersistenceObjectException_Hibernate_Spring Boot_Spring Data Jpa - Fatal编程技术网

Hibernate 测试中带有@MapsId注释的子实体中的PersistenceObjectException

Hibernate 测试中带有@MapsId注释的子实体中的PersistenceObjectException,hibernate,spring-boot,spring-data-jpa,Hibernate,Spring Boot,Spring Data Jpa,我有以下两个实体,父实体和子实体。父项没有字段子项 子实体的定义如下: @Entity @Table(name = "child") @Audited public class Child extends BaseEntity { @OneToOne @JoinColumn(name = "application_id") @MapsId @NotAudited private Parent parent; .... 我正在编写一个测试,我想创建一个父

我有以下两个实体,父实体和子实体。父项没有字段子项

子实体的定义如下:

@Entity
@Table(name = "child")
@Audited
public class Child extends BaseEntity {

    @OneToOne
    @JoinColumn(name = "application_id")
    @MapsId
    @NotAudited
    private Parent parent;
....
我正在编写一个测试,我想创建一个父实体和一个子实体,并保存它们。因此,我做了以下工作:

parentRepository.save(parent);

Child child = new Child(parent);
childService.save(child);
但是,我得到了以下错误:

org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: io.manuel.Parent; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: io.manuel.Parent

问题是,如果我删除注释@MapsId,它就会工作。我必须做什么才能使它与注释一起工作?

您需要这样做

Parent savedParent = parentRepository.save(parent);

Child child = new Child(savedParent);
childService.save(child);
您必须获得持久化对象并使用它。这就是异常所说的,您正在传递一个分离的(不是持久的)实体来保存。这是一个实体可以是的不同状态的一张很好的图片