Hibernate:CascadeType.ALL由于OneToOne关系中的PERSIST而未保存所有实体

时间:2016-12-27 10:42:09

标签: java spring hibernate spring-data-jpa

使用以下属性:

@Entity
@Table(name = "b")
public class B extends AbstractEntity implements Serializable, Comparable<B>, Cloneable {
  ...
  @JsonBackReference
  @OneToOne
  @JoinColumn(name ="a_id")
  @Cascade( value = { CascadeType.ALL } )
  private A an;
}

@Entity
@Table(name = "a")
public class A implements Serializable{
  @Id
  @Column(name="a_id")
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;

  @OneToOne(mappedBy = "a", fetch = FetchType.LAZY, orphanRemoval = true)
  private B b;
}

它只保存第一个实体,之后它会为其他实体返回此错误:

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

我不熟悉PERSIST。我不知道是否仅使用CascadeType.MERGE或CascadeType.SAVE_UPDATE来解决问题,我的意思是它们有效,但我宁愿知道如何修复持久性。

1 个答案:

答案 0 :(得分:0)

您如何尝试保存或实体?通过调用&#34; SaveOrUpdate&#34;方法或&#34;坚持&#34; ?