JPA删除数据库中行的更多问题

时间:2018-07-26 15:17:11

标签: java hibernate jpa

我有以下代码定义了三个表之间的关系。

public class Attachment implements Serializable {
  @Id
  @Column(name="attachment_id")
    private int attachmentId;

  @ManyToOne(cascade=CascadeType.ALL)
  @JoinColumn(name="reference_id")
  private Reference reference;

  @OneToMany(mappedBy="attachment")
    private List<Reference> references;

  MORE STUFF;
}

public class Uuid implements Serializable {

  @Id
  @Column("name=uuid_id")
  @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int uuidId;

  @ManyToOne(cascade=CascadeType.ALL)
  @JoinColumn(name="reference_id")
  private Reference reference;

  MORE STUFF
}

public class Reference implements Serializable {
  @Id
  @Column(name="reference_id")
  @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int referenceId;

  @OneToMany(mappedBy="reference")
  private List<Attachment> attachments;

  @ManyToOne(cascade=CascadeType.MERGE)
  @JoinColumn(name="attachment_id")
  private Attachment attachment;

  @OneToMany(mappedBy="reference")
  private List<Uuid> uuids;

  MORE STUFF
}

我还有更多代码来选择需要删除的特定“ uuid”对象/行,其想法是其他表中由于共享相同的reference_id而需要删除的所有内容也应删除。这样做的代码是:

try {
  final EntityTransaction transaction = em.getTransaction();

  transaction.begin();
  em.remove(data);
  transaction.commit();
} catch (final PersistenceException e) {
   throw new CPDPersistenceException(e);
}

执行删除操作时会引发异常“无法删除或更新父行:外键约束失败。我之前在此方法的变体上发布过一些内容。有人有任何想法吗?谢谢您的时间。

1 个答案:

答案 0 :(得分:0)

您在ReferenceAttachment之间定义了一对多的关系,但在ReferenceAttachment之间定义了一对多的关系(以及恶习与) ,这将永远行不通。您应该拥有其中之一,而不是两者都有,或者是多对多关系。

解决此问题,删除对象应该容易得多。

例如:

public class Attachment implements Serializable {
  @Id
  @Column(name="attachment_id")
  private int attachmentId;

  @ManyToOne(cascade=CascadeType.ALL)
  @JoinColumn(name="reference_id")
  private Reference reference;

  //MORE STUFF;
}

public class Reference implements Serializable {
  @Id
  @Column(name="reference_id")
  @GeneratedValue(strategy=GenerationType.IDENTITY)
  private int referenceId;

  @OneToMany(mappedBy="reference")
  private List<Attachment> attachments;

  @OneToMany(mappedBy="reference")
  private List<Uuid> uuids;

  /bMORE STUFF
}