我在代码中有以下实体和关系,
图书.java
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Entity
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
@OneToMany(mappedBy = "book", fetch = FetchType.LAZY)
private Set<BookPublisher> bookPublishers = new HashSet<>();
public Book(String name) {
this.name = name;
}
}
BookPublisher.java
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Entity
@Table(name = "book_publisher")
public class BookPublisher {
@EmbeddedId
private BookPublisherId id;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@MapsId("bookId")
@JoinColumn(name = "book_id")
private Book book;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@MapsId("publisherId")
@JoinColumn(name = "publisher_id")
private Publisher publisher;
@Column(name = "published_date")
private Date publishedDate;
public BookPublisher(Book book, Publisher publisher, Date publishedDate) {
this.id = new BookPublisherId(book.getId(), publisher.getId());
this.book = book;
this.publisher = publisher;
this.publishedDate = publishedDate;
}
}
Publisher.java
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Entity
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Publisher {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
@OneToMany(mappedBy = "publisher", fetch = FetchType.LAZY)
private Set<BookPublisher> bookPublishers = new HashSet<>();
public Publisher(String name) {
this.name = name;
}
}
BookPublisherId.java
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Embeddable
public class BookPublisherId implements Serializable {
@Column(name = "book_id")
private Integer bookId;
@Column(name = "publisher_id")
private Integer publisherId;
}
问题 1: 插入按 Book、Publisher、BookPublisher 的顺序正常工作。但是 findAll() 不会返回任何存储库的结果,它会导致查询下面的语句总是循环的,使用:
select bookpublis0_.book_id as book_id1_1_0_, bookpublis0_.publisher_id as publishe2_1_0_, bookpublis0_.book_id as book_id1_1_1_, bookpublis0_.publisher_id as publishe2_1_1_, bookpublis0_.published_date as publishe3_1_1_ from book_publisher bookpublis0_ where bookpublis0_.book_id=?
怎么了?
问题2: 如何查询图书对象的Publisher ID =?具有以下对象结构?findBookByPublisherID("1")
{
"book_id": "1",
"publishers": [
{
"publisher_id": "1",
...
},
{
"publisher_id": "2",
...
}
]
}