Hibernate - 来自镜像(反向)类的Cascade.REMOVE

时间:2016-04-09 01:01:26

标签: java hibernate jpa

我有A和B类如下:

@Entity
public class A implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer idd;
    public Integer getIdd() { return idd;   }
    public void setIdd(Integer idd) { this.idd = idd;   }

    @OneToOne(mappedBy="a")
    @Cascade(CascadeType.REMOVE)   
    //@Transient   
    private B b;
    public B getB() {  return b;  }
    public void setB(B b) {  this.b = b;  }

    private int someField;
    public int getSomeField() {  return someField;  }
    public void setSomeField(int someField) {  this.someField = someField;  }

    public A(int someField) { this.someField = someField;   }
    public A() {}

}

@Entity
public class B implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    public Integer getId() { return id; }
    public void setId(Integer id) { this.id = id;  }

    @OneToOne(targetEntity = db.entityClasses.A.class)
    @JoinColumn(name = "idd", nullable = true)
    private A a;
    public A getA() {  return a;   }
    public void setA(A a) {  this.a = a;   } 

    private int ssomeField;
    public int getSsomeField() {  return ssomeField;    }
    public void setSsomeField(int someField) {  this.ssomeField = someField;  }

    public B() { }
    public B(A a, int ssomeField) {
    this.a = a;
    this.ssomeField = ssomeField;
    }
}

因此,BA一对一关联,B是所有者。 我删除B行时,我希望删除A的相应行。 为此,我在A上级联了删除。

所有其他 - 这些表的插入,以及AB没有外键引用时从id=5删除工作正常。

但是,当我想要删除一行时,请说A B的行和A有一个FK引用。到com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`PrjTEMP`.`b`, CONSTRAINT `FK4253917D0F` FOREIGN KEY (`idd`) REFERENCES `a` (`idd`)) 那一排,我得到了以下错误:

{{1}}

这段代码有什么问题???

1 个答案:

答案 0 :(得分:-2)

正在删除查询。删除()成功了。