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!
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();
}
}
}
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.