Reputation: 65
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?
Upvotes: 0
Views: 1776
Reputation: 991
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.
Upvotes: 1