Home > Software design >  JPA Inheritance - I want to delete parent row with child rows how do I do it
JPA Inheritance - I want to delete parent row with child rows how do I do it

Time:10-08

Parent Class

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class OnlinePost {
    @Id
    @SequenceGenerator(
            name = "onlinePost_sequence",
            sequenceName = "onlinePost_sequence",
            allocationSize = 1
    )
    @GeneratedValue(
            strategy = GenerationType.SEQUENCE,
            generator = "onlinePost_sequence"
    )
    private Long postId;
    // some other columns, getters and setters

}

Child Class

public class Post extends OnlinePost{
    private String image;
    private String title;
}

I want to delete the parent, then delete child element automatically

CodePudding user response:

You can do the following. Instead of extending you can map the entity together like below

@Entity
public class OnlinePost {
    @Id
    @SequenceGenerator(
            name = "onlinePost_sequence",
            sequenceName = "onlinePost_sequence",
            allocationSize = 1
    )
    @GeneratedValue(
            strategy = GenerationType.SEQUENCE,
            generator = "onlinePost_sequence"
    )
    private Long postId;
    // some other columns, getters and setters

    @OneToOne(cascade= CascadeType.DELETE)
    Post post;
}

public class Post{
    private String image;
    private String title;
}

By doing this when you delete parent . The child will be deleted automatically

CodePudding user response:

Create a child field in your parent class then map both class and apply cascade type delete in your relation to achieve the desired output example:

//for One to one:

@OneToOne(cascade= CascadeType.DELETE)
private Post post;
  • Related