Spring JPA删除@OneToOne关系

时间:2019-03-21 08:23:23

标签: hibernate spring-boot spring-mvc jpa spring-data-jpa

我有一个SpringBoot 2.1.3.RELEASE RESTful Web Service应用程序,它使用Spring Initializer,嵌入式Tomcat,Thymeleaf模板引擎以及作为可执行JAR文件的软件包,我有这个对象:

public class ImpactHint implements Serializable {



    @OneToOne(mappedBy = "impactHint", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "IA_ID")
    private ImpactHintAmendment amendment ;


...

}

还有

public class ImpactHintAmendment implements Serializable, IEntity<String> {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "ID")
    private String id;

    @OneToOne(cascade = {CascadeType.ALL})
    @JoinColumn(name = "IA_ID")
    private ImpactHint impactHint;  
..
}

我正在尝试使用

删除
em.remove(impactHint.getAmendment());
em.persist(impactHint);

还有

impactHint.setAmendment(null);
em.persist(impactHint);

在我的存储库类中,但没有任何作用

@Repository
public class ImpactHintDao extends AbstractDao<ImpactHint, String> implements IImpactHintDao {


    @PersistenceContext
    private EntityManager em;

   ..
}

1 个答案:

答案 0 :(得分:0)

对于OneToOne双向,使用mappedBy属性定义逆映射。拥有实体ImpactHint使用@JoinColumn并具有FK列。第二实体:

public class ImpactHintAmendment {
    @OneToOne(mappedBy = "amendment")
    private ImpactHint impactHint; 

如果您更正了映射,则删除孤儿attr。应该删除Amendment而不调用remove

impactHint.setAmendment(null);
em.persist(impactHint);