简体   繁体   中英

JPA joined table inheritance and full data integrity

Consider the following JPA joined table inheritance example from here在此处输入图像描述

Java code:

@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 code:

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)

They say in the article

The JOINED table inheritance strategy addresses the data integrity concerns because every subclass is associated with a different table.

However, as I understand in this example we provide only one half of data integrity protection at the level of DB. For example, we can't delete Shape and leave Circle/Rectangle but we can delete Circle/Rectangle and leave Shape. So, as I understand we don't have 100% data integrity protection.

Is there a way to provide full data integrity protection with joined table inheritance in JPA/Hibernate?

If your premise is that somebody will delete the data with a query in the wrong table, then no, there isn't.

But if you delete an entity using entityManager.remove(...) , Hibernate ORM will delete the rows from the right tables.

The problem is that the table Shape cannot have a single foreign key constraint that refers to 2 different tables (as far as I know).

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