繁体   English   中英

JPA 加入表 inheritance 和完整的数据完整性

[英]JPA joined table inheritance and full data integrity

考虑以下 JPA 连接表 inheritance 示例从这里在此处输入图像描述

Java代码:

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Shape {

    @Id
    @Column(name = "vehicle_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

}

@Entity
public class Circle extends Shape {

    private double radius;

    + constructor/getters/setters
}

@Entity
public class Rectangle extends Shape {

    private double width;
    private double length;
  
   + constructor/getters/setters
}

SQL 代码:

create table Circle (
    radius double precision not null,
    shape_id integer not null,
    primary key (shape_id)
)

create table Rectangle (
    length double precision not null,
    width double precision not null,
    shape_id integer not null,
    primary key (shape_id)
)

create table Shape (
    shape_id integer not null auto_increment,
    primary key (shape_id)
)

alter table Circle 
    add constraint FK2nshngrop6dt5amv1egecvdnn 
    foreign key (shape_id) 
    references Shape (shape_id)

alter table Rectangle 
    add constraint FKh3gkuyk86e8sfl6ilsulitcm5 
    foreign key (shape_id) 
    references Shape (shape_id)

他们在文章中说

JOINED 表 inheritance 策略解决了数据完整性问题,因为每个子类都与不同的表相关联。

但是,正如我在此示例中所了解的,我们仅在 DB 级别提供了一半的数据完整性保护。 例如,我们不能删除Shape并离开Circle/Rectangle,但我们可以删除Circle/Rectangle并离开Shape。 因此,据我了解,我们没有 100% 的数据完整性保护。

有没有办法通过 JPA/Hibernate 中的连接表 inheritance 提供完整的数据完整性保护?

如果您的前提是有人会在错误的表中使用查询删除数据,那么不,没有。

但是,如果您使用entityManager.remove(...)删除实体, Hibernate ORM 将从右表中删除行。

问题是表Shape不能有一个引用 2 个不同表的外键约束(据我所知)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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