You need to model the book_publisher table as an entity with 2 many-to-one relationships to the Book and Publisher entities.
@Entity classBookPublisher{ @EmbeddedId private BookPublisherId id = new BookPublisherId(); @ManyToOne @MapsId("bookId") private Book book; @ManyToOne @MapsId("publisherId") private Publisher publisher; private Format format; ... }
@Embeddable publicstaticclassBookPublisherIdimplementsSerializable{ privatestaticfinallong serialVersionUID = 1L; private Long bookId; private Long publisherId; publicBookPublisherId(){ } publicBookPublisherId(Long bookId, Long publisherId){ super(); this.bookId = bookId; this.publisherId = publisherId; } public Long getBookId(){ return bookId; } publicvoidsetBookId(Long bookId){ this.bookId = bookId; } public Long getPublisherId(){ return publisherId; } publicvoidsetPublisherId(Long publisherId){ this.publisherId = publisherId; } @Override publicinthashCode(){ finalint prime = 31; int result = 1; result = prime * result + ((bookId == null) ? 0 : bookId.hashCode()); result = prime * result + ((publisherId == null) ? 0 : publisherId.hashCode()); return result; } @Override publicbooleanequals(Object obj){ if (this == obj) returntrue; if (obj == null) returnfalse; if (getClass() != obj.getClass()) returnfalse; BookPublisherId other = (BookPublisherId) obj; return Objects.equals(getBookId(), other.getBookId()) && Objects.equals(getPublisherId(), other.getPublisherId()); } }
Mapping as a Bidirectional Association
@Entity publicclassBook{ @Id @GeneratedValue private Long id; @OneToMany(mappedBy = "publisher") private Set<BookPublisher> bookPublishers = new HashSet<>(); ... }
@Entity publicclassPublisher{ @Id @GeneratedValue private Long id; @OneToMany(mappedBy = "publisher") private Set<BookPublisher> bookPublishers = new HashSet<>(); ... }
Using the Mapping
Book b = new Book(); b.setTitle("Hibernate Tips - More than 70 solutions to common Hibernate problems"); em.persist(b); Publisher p = new Publisher(); p.setName("Thorben Janssen"); em.persist(p); BookPublisher bp = new BookPublisher(); bp.setBook(b); bp.setPublisher(p); p.getBookPublishers().add(bp); b.getBookPublishers().add(bp);