How to cascade delete entities with unidirectional 'ManyToOne' relationship with JPA

穿精又带淫゛_ 提交于 2020-01-04 04:15:12

问题


I have two entity classes 'User' and 'Department' with unidirectional 'ManyToOne' relationship as below.

public class User{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "DEPARTMENT_ID", nullable = true)
    private Department department;
}

public class Department{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
}

If I want to delete some users and cascade remove the referenced departments if not any user references the department, is there any features of JPA to use please?


回答1:


You can use CascadeType.DELETE, however this annotation only applies to the objects in the EntityManager, not the database. You want to be sure that ON DELETE CASCADE is added to the database constraint. To verify, you can configure JPA to generate a ddl file. Take a look at the ddl file, you'll notice that ON DELETE CASCADE is not part of the constraint. Add ON DELETE CASCADE to actual SQL in the ddl file, then update your database schema from the ddl. This will fix your problem .

This link shows how to use ON DELETE CASCADE on for CONSTRAINT in MySQL. You do this on the constraint. You can also do it in a CREATE TABLE or ALTER TABLE statement. It's likely that JPA creates the constraint in an ALTER TABLE statement. Simply add ON DELETE CASCADE to that statement.

Note that some JPA implementors do provide a means for this functionality.

Hibernate does supply this functionality using the @OnDelete annotation.




回答2:


You can tell hibernate to delete 'orphan' entries with;

@Cascade({ org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN })


来源:https://stackoverflow.com/questions/19626535/how-to-cascade-delete-entities-with-unidirectional-manytoone-relationship-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!