gpt4 book ai didi

Spring JPARepository 查询多对多交集表

转载 作者:行者123 更新时间:2023-12-05 01:44:03 25 4
gpt4 key购买 nike

我有如下 3 个实体类(示例取自 https://hellokoding.com/jpa-many-to-many-extra-columns-relationship-mapping-example-with-spring-boot-maven-and-mysql/)

读书课

@Entity
public class Book{
private int id;
private String name;
private Set<BookPublisher> bookPublishers;

public Book() {
}

public Book(String name) {
this.name = name;
bookPublishers = new HashSet<>();
}

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@OneToMany(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true)
public Set<BookPublisher> getBookPublishers() {
return bookPublishers;
}

public void setBookPublishers(Set<BookPublisher> bookPublishers) {
this.bookPublishers = bookPublishers;
}
}

发布者类

@Entity
public class Publisher {
private int id;
private String name;
private Set<BookPublisher> bookPublishers;

public Publisher(){

}

public Publisher(String name){
this.name = name;
}

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@OneToMany(mappedBy = "publisher")
public Set<BookPublisher> getBookPublishers() {
return bookPublishers;
}

public void setBookPublishers(Set<BookPublisher> bookPublishers) {
this.bookPublishers = bookPublishers;
}
}

交集表

@Entity
@Table(name = "book_publisher")
public class BookPublisher implements Serializable{
private Book book;
private Publisher publisher;
private Date publishedDate;

@Id
@ManyToOne
@JoinColumn(name = "book_id")
public Book getBook() {
return book;
}

public void setBook(Book book) {
this.book = book;
}

@Id
@ManyToOne
@JoinColumn(name = "publisher_id")
public Publisher getPublisher() {
return publisher;
}

public void setPublisher(Publisher publisher) {
this.publisher = publisher;
}

@Column(name = "published_date")
public Date getPublishedDate() {
return publishedDate;
}

public void setPublishedDate(Date publishedDate) {
this.publishedDate = publishedDate;
}
}

我想查询两件事,

  1. 获取属于特定出版商的图书列表,例如获取与出版商 100 关联的所有图书
  2. 获取与特定出版商无关的图书列表,例如获取所有与出版商无关的图书 100

如果可能的话,我想使用简单的 JPARepository 查询来实现这一点,例如 findByXYZIn(...) 等。

请告诉我是否可以使用 JPA 存储库查询来查询多对多关系,如果可以,我是否可以直接执行此操作还是需要对实体类进行任何更改

最佳答案

BookRepository

获取出版商的书籍

findBooksByBookPublishersPublisherId(长型 publisherId)

获取非出版商出版的图书

findBooksByBookPublishersPublisherIdNot(Long publisherId)

恕我直言 PublicationBookPublisher 更合适,在你的情况下 Publisher 本身可以是 BookPublisher (a published 即出版书籍)

关于Spring JPARepository 查询多对多交集表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47355415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com