0

Is it possible to Greate DDL using JPA with bidirectional mapping and without foreign key? If can, is it best practice?

@Entity
class Book{
    int id;
    String title;
    @OneToMany(mappedBy="book")
    Set<BookDetail> book_detail;
}

@Entity
class BookDetail{
    int id;
    String name;
    String description;
    @ManyToOne
    Book book;
}
Shakthi
  • 826
  • 3
  • 15
  • 33

2 Answers2

0

You can't do it without at least one foreign key, since a DB needs to establish some connection between two entities - BookDetail and Book. It is possible to create two tables for these entities without a real foreign key by using plain integer attribute in BookDetail which will be storing a value of Book's id. But don't do that!
With a foreign key your DBMS generates constraints so it's known about the relationship and it prevents some unsafe deletions and insertions, so each BookDetail's row references existing Books one.
Without real foreign key you c accidentally remove a Book and you BookItem's

Andrey Antipov
  • 370
  • 3
  • 9
0

Yes. It is possible using a join table. It will have foreign keys of course.

@Entity
class Book{

    @OneToMany
    List<BookDetail> bookDetail;

}

@Entity
class BookDetail{

    @ManyToOne(fetch = FetchType.LAZY)
    Book book;

}

what is @JoinColumn and how it is used in Hibernate

v.ladynev
  • 19,275
  • 8
  • 46
  • 67