简体   繁体   中英

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]; constraint [fk5o18odcs53r4t69hbgf35haj3]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement

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. Do I have to define the constraint types directly by sql? Can JPA Hibernate not define these constraints?

You need to specify mappedBy parameter for Workspace class OneToMany relation.

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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