【问题标题】:JPA joined table inheritance and full data integrityJPA 联接表继承和完整的数据完整性
【发布时间】:2021-05-01 13:36:26
【问题描述】:

考虑以下来自here 的 JPA 连接表继承示例

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 表继承策略解决数据完整性问题 担心,因为每个子类都与不同的表相关联。

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

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

【问题讨论】:

    标签: java sql hibernate jpa


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多