简体   繁体   中英

JPA: On delete cascade @OneToMany relationship EclipseLink

I have these two entity classes:

@Entity
@Table(name = "USER")
@XmlRootElement
@CascadeOnDelete
public class User implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 15)
    @Column(name = "USERNAME")
    private String username;
    //...
    @OneToMany(mappedBy = "username", cascade = CascadeType.ALL, orphanRemoval=true)
    @CascadeOnDelete
    private Collection<Post> postCollection;
    //...
}

And:

@Entity
@Table(name = "POST")
@XmlRootElement
public class Post implements Serializable {
    // ...
    @JoinColumn(name = "USERNAME", referencedColumnName = "USERNAME")
    @ManyToOne
    private User username;
    //...
}

I have some posts attached to the same user. If I delete one of them it works right. But when I try to delete that user from the DB (using the EntityManager) I get java.sql.SQLIntegrityConstraintViolationException foreign key violation restriction. Is there a way to delete all that posts when the user (their foreign key) is deleted? Simply an ON DELETE CASCADE SQL statement. I'm using Derby (Java DB) and EclipseLink. Adding those @CascadeOnDelete annotations from JPA Extensions for EclipseLink is the last thing I've tried, with no success at all.

EDIT: This is the code I use for removing an user (it´sa REST API)

@DELETE
@Path("{id}")
public Response remove(@PathParam("id") String id) {
    User u;
    if((u = super.find(id)) == null)
        return Response.status(Response.Status.NOT_FOUND).build();
    super.remove(u);
    return Response.status(Response.Status.NO_CONTENT).build();

}

And, in the superclass:

public void remove(T entity) {    
    getEntityManager().remove(getEntityManager().merge(entity));
}

Can we try adding the ON DELETE SET NULL clause to the foreign key constraint in the POST table. This would help to set the corresponding records in the child table to NULL when the data in the parent table is deleted. So if a username value is deleted from the user table, the corresponding records in the POST table that use this username will have the username set to NULL.

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