我试图从我的数据库中返回所有书籍,但是一旦我将值插入名为COLLECTION的连接表(用于解决BOOK和USER之间的多对多Rel),我收到的输出看起来就像一个循环(用邮差)。
书籍实体的实施:
@Getter
@Setter
@ToString
@EqualsAndHashCode
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Book {
@Id
private Integer id;
private String title;
private String author;
private String description;
@OneToMany(mappedBy = "book", cascade = CascadeType.ALL)
private Set<Collection> collections;
public Book(String title, String author, String description) {
this.title = title;
this.author = author;
this.description = description;
}
public Book(String title, String author Collection... collections){
this.title = title;
this.author = author;
for (Collection collection : collections){
collection.setBook(this);
}
this.collections = Stream.of(collections).collect(Collectors.toSet());
}
}
用户实体的实现:
@Getter
@Setter
@NoArgsConstructor
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String email;
private String password;
private String username;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private Set<Collection> collections = new HashSet<>();
public User(String username, String password) {
this.username = username;
this.password = password;
}
}
收集实体:
@Getter
@Setter
@NoArgsConstructor
@Entity
public class Collection implements Serializable {
@Id
@ManyToOne
@JoinColumn
private Book book;
@Id
@ManyToOne
@JoinColumn
private User user;
public Collection(User user){
this.user = user;
}
@Override
public boolean equals(Object o){
if(this == o) return true;
if(!(o instanceof Collection)) return false;
Collection that = (Collection) o;
return Objects.equals(book.getTitle(), that.book.getTitle()) &&
Objects.equals(book.getAuthor(), that.book.getAuthor()) &&
Objects.equals(user.getUsername(), that.user.getUsername());
}
@Override
public int hashCode(){
return Objects.hash(book.getTitle(), book.getAuthor(), user.getUsername());
}
}
最后还有Book Depository:
@Transactional
@Repository
public interface BookRepository extends JpaRepository<Book, Integer> {
// this causes sql syntax error
// @Query(value = "SELECT b.id, b.title, b.author FROM book b", nativeQuery = true)
// List<Book> getAllBooks();
// this returns the loopy output from postman detailed below
List<Book> findAll();
}
我在Postman中收到的输出看起来像一个循环:
[{"id":1,"title":"Pride and Prejudice","author":"Jane Austen","users":[{"id":1,"email":"[email protected]","password":"$2a$10$BVXUCumzWyec9zEUeCv1r.m2pFwvAe7Cp1dLjiGfXuEEIHkhn3jHO","username":"user","books":[{"id":1,"title":"Pride and Prejudice","author":"Jane Austen", "users":[{"id":1,"email":"[email protected]","password":"$2a$10$BVXUCumzWyec9zEUeCv1r.m2pFwvAe7Cp1dLjiGfXuEEIHkhn3jHO, "username":"user","books": .......
预期输出应该是我在数据库中拥有的所有书籍的列表。
要设置book和user之间的关系,请使用@ManyToMany映射设置直接关系。作为参考,您可以选择以下链接 -
https://www.callicoder.com/hibernate-spring-boot-jpa-many-to-many-mapping-example/
此外,您不需要显式定义findAll(),Jpa存储库本身也提供了这些通用方法。