Hibernate 5.2在表postgres上级联删除

时间:2018-09-13 12:04:13

标签: java postgresql hibernate jpa

我有两个相互依赖的类。我想进行级联删除。这个问题,我有以下错误:

  

无法执行语句; SQL [n / a];约束[fk5o18odcs53r4t69hbgf35haj3];嵌套的异常是org.hibernate.exception.ConstraintViolationException:无法执行语句

public class Workspace {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", nullable = false, updatable = false)
    private Long id;

    @Column(name = "name", nullable = false, unique = true)
    private String name;

    private String description;

    @CreationTimestamp
    @Column(name = "created_at")
    private Date createdAt;

    @UpdateTimestamp
    @Column(name = "updated_at")
    private Date updatedAt;

    @OneToMany( fetch = FetchType.LAZY,cascade = CascadeType.REMOVE,orphanRemoval = true)
    private List<Project> projects;


    public void setId(Long id) {
        this.id = id;
    }

    public List<Project> getProjects() {
        return projects;
    }


    public void setProjects(List<Project> projects) {
        this.projects = projects;
    }

}
@Entity
@Table(name = "project")
public class Project {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", nullable = false, updatable = false)
private Long id;

@Column(name = "name", nullable = false)
private String name;

@ManyToOne(fetch = FetchType.LAZY)
private Workspace workspace;

private String description;

@CreationTimestamp
@Column(name = "created_at")
private Date createdAt;

@UpdateTimestamp
@Column(name = "updated_at")
private Date updatedAt;

问题是使用我的JPA创建的表未在删除规则中定义级联类型。 我是否必须直接通过sql定义约束类型? JPA Hibernate可以不定义这些约束吗?

1 个答案:

答案 0 :(得分:0)

您需要为Workspace类OneToMany关系指定mapByBy参数。

@OneToMany( fetch = FetchType.LAZY,cascade = CascadeType.REMOVE,orphanRemoval = true, mappedBy = "workspace") 
private List<Project> projects;

然后,您可以删除工作区,所有项目也将被删除。