简体   繁体   English

Hibernate 5.2在表postgres上级联删除

[英]Hibernate 5.2 delete on cascade on my tables postgres

I have two classes that depend on each other. 我有两个相互依赖的类。 and I want to do a cascade delete. 我想进行级联删除。 the problem I have the following error : 问题我有以下错误:

could not execute statement; 无法执行语句; SQL [n/a]; SQL [n / a]; constraint [fk5o18odcs53r4t69hbgf35haj3]; 约束[fk5o18odcs53r4t69hbgf35haj3]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement 嵌套的异常是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;

The problem is that the tables created with my JPA dont define the cascade type in the delete rules. 问题是用我的JPA创建的表没有在删除规则中定义级联类型。 Do I have to define the constraint types directly by sql? 我是否必须直接通过sql定义约束类型? Can JPA Hibernate not define these constraints? JPA Hibernate可以不定义这些约束吗?

You need to specify mappedBy parameter for Workspace class OneToMany relation. 您需要为Workspace类OneToMany关系指定mapBy参数。

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

And after that you could delete workspace and all projects will be deleted as well. 之后,您可以删除工作区,所有项目也将被删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM