hibernate CompositeKey

hibernate CompositeKey

https://www.baeldung.com/hibernate-many-to-many

https://www.baeldung.com/jpa-many-to-many

https://thorben-janssen.com/hibernate-tip-many-to-many-association-with-additional-attributes/

Many to many with addtional attributes

Screen Shot 2020-11-26 at 11.20.18 PM

JoinTable 无法添加新属性

You need to model the book_publisher table as an entity with 2 many-to-one relationships to the Book and Publisher entities.

@Entity
class BookPublisher {

@EmbeddedId
private BookPublisherId id = new BookPublisherId();

@ManyToOne
@MapsId("bookId")
private Book book;

@ManyToOne
@MapsId("publisherId")
private Publisher publisher;

private Format format;

...
}

@Embeddable
public static class BookPublisherId implements Serializable {

private static final long serialVersionUID = 1L;

private Long bookId;
private Long publisherId;

public BookPublisherId() {

}

public BookPublisherId(Long bookId, Long publisherId) {
super();
this.bookId = bookId;
this.publisherId = publisherId;
}

public Long getBookId() {
return bookId;
}

public void setBookId(Long bookId) {
this.bookId = bookId;
}

public Long getPublisherId() {
return publisherId;
}

public void setPublisherId(Long publisherId) {
this.publisherId = publisherId;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((bookId == null) ? 0 : bookId.hashCode());
result = prime * result
+ ((publisherId == null) ? 0 : publisherId.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BookPublisherId other = (BookPublisherId) obj;
return Objects.equals(getBookId(), other.getBookId()) && Objects.equals(getPublisherId(), other.getPublisherId());
}
}


Mapping as a Bidirectional Association

@Entity
public class Book {

@Id
@GeneratedValue
private Long id;

@OneToMany(mappedBy = "publisher")
private Set<BookPublisher> bookPublishers = new HashSet<>();

...
}

@Entity
public class Publisher {

@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);