无法删除或更新双向关系

时间:2017-08-08 16:27:05

标签: java mysql hibernate jpa

我有三张桌子:

CREATE TABLE IF NOT EXISTS `DB`.`global_history` (
  `ID` INT(11) AUTO_INCREMENT,
  `ID_HISTORY` INT(11) NULL,

  PRIMARY KEY (`ID`),

  CONSTRAINT `FK_HISTORY_GLOBAL_HISTORY`
    FOREIGN KEY (`ID_HISTORY`)
    REFERENCES `DB`.`history` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION);

第二张表:

CREATE TABLE IF NOT EXISTS `DB`.`history` (
  `ID` INT(11) AUTO_INCREMENT,
  `TIMESTAMP` DATETIME NOT NULL,
  PRIMARY KEY (`ID`));*

第三张表:

CREATE TABLE IF NOT EXISTS `DB`.`audit` (
  `ID` INT(11) AUTO_INCREMENT,
  `ID_HISTORY` INT(11) NULL,

  PRIMARY KEY (`ID`),

  CONSTRAINT `FK_HISTORY_AUDIT`
    FOREIGN KEY (`ID_HISTORY`)
    REFERENCES `DB`.`history` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION);

这些是我的模型类:

全球历史:

@ManyToOne
@JoinColumn(name = "ID_HISTORY", nullable = true)
private History history;

历史记录:

    @OneToMany(mappedBy = "history", fetch = FetchType.EAGER, cascade = { CascadeType.ALL })
@Fetch(value = FetchMode.SUBSELECT)
@Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE })
private List<GloabalHistory> globalHistories;

@ManyToOne
@JoinColumn(name = "ID_AUDIT", nullable = true)
private Audit audit;

审核:

    @OneToMany(mappedBy = "audit", fetch = FetchType.EAGER, cascade = { CascadeType.ALL })
@Fetch(value = FetchMode.SUBSELECT)
@Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE })
private List<History> histories;

但是当我尝试更新History(第二个表)中的一行时,我收到此错误:

  

- &GT;无法删除或更新父行:外键约束失败

1 个答案:

答案 0 :(得分:0)

您需要在所有一对多关系中使用cascade = CascadeType.ALL,并在服务类中使用@Transactional注释,并在save方法上使用@Transactional(propagation = Propagation.REQUIRED)。并且还在hibernate或Spring配置上启用事务。