本文介绍了如何级联与JPA单向“ManyToOne”关系的删除实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个实体类'User'和'Department',具有单向'ManyToOne'关系,如下所示。

  public class用户{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
私有长ID;

@ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY)
@JoinColumn(name =DEPARTMENT_ID,nullable = true)
私人部门部门;
}

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

$ / code>

如果我想要删除一些用户并级联移除引用的部门用户引用部门,是否有JPA的任何功能使用请? 您可以使用 CascadeType .DELETE ,但是此注释仅适用于 EntityManager 中的对象,而不适用于数据库。您要确保将 ON DELETE CASCADE 添加到数据库约束中。要验证,您可以配置JPA生成一个ddl文件。看看 ddl 文件,你会注意到 ON DELETE CASCADE 不是约束的一部分。将 ON DELETE CASCADE 添加到 ddl 文件中的实际SQL,然后从ddl更新数据库模式。这将解决您的问题。



显示了如何在 CONSTRAINT ON DELETE CASCADE 在MySQL中。你在约束上做到这一点。您还可以在 CREATE TABLE ALTER TABLE 语句中执行此操作。 JPA很可能在 ALTER TABLE 语句中创建约束。只需在该语句中添加 ON DELETE CASCADE 即可。

请注意,某些JPA实现者提供了此功能的一种手段。


Hibernate确实使用 @OnDelete 注释来提供此功能。


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?

解决方案

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.

这篇关于如何级联与JPA单向“ManyToOne”关系的删除实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 01:28