user1119859
user1119859

Reputation: 719

JPA Foreign Key OneToMany

I have two entities, which are connected as a one to many relationship.

public class Book{
  @OneToMany(mappedBy = "book")
  private List<Page> pages;
}

public class Page{
  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "book_id")
  public Book book;
}

So, a book can't be deleted if a page refers that book. But how can I prevent pages beeing deleted as long as they reference a book ?

I'd like to have a foreign key constraint that prevents page objects to be deleted as long as they refer to any book.

Thanks for your help!

Upvotes: 0

Views: 108

Answers (1)

Mehdi Ayari
Mehdi Ayari

Reputation: 548

I have a solution for this using @PreRemove. This way it will prevent Pages from being deleted if they are linked to a book.

BookRelationShipExist : It's just an exception that you can create, you can also throw any other type of Exception

public class Page{
     @ManyToOne(fetch = FetchType.LAZY)
     @JoinColumn(name = "book_id")
     public Book book;

     @PreRemove
     private void preRemove() {
         if (book != null) {
               throw new BookRelationShipExist();
         }
     }
 }

Upvotes: 1

Related Questions