gpt4 book ai didi

spring-data-rest - 成功添加带有父引用的子实体后,子实体不显示在父资源下

转载 作者:行者123 更新时间:2023-12-04 08:35:37 24 4
gpt4 key购买 nike

我有两个实体,Shelf 和 Book。一个 Shelf 可以有多个 Books(关系是双向的)。我已将这两个公开为 JpaRepositories。

问题是:

  1. 我通过将 { "name":"sci-fi"} 发布到/shelves 创建了一个书架。(成功)
  2. 我通过将 { "name":"mybook", "shelf":"localhost:8080/shelves/1"} 发布到/books 来为那个书架创建一本书。 (成功)
  3. 当我在/books/1 上拿到我刚创建的书时,它有指向父书架的正确链接。
  4. 但是当我去 shelves/1/books 时,我得到一个空的结果,{ }!

有什么我可能遗漏的想法吗?

现在我已经通过在 beforeCreate 事件中显式地将书添加到书架来构造一个解决方法,但看起来这应该是完全没有必要的。 (但是,它确实解决了问题。)

@HandleBeforeCreate(Book.class)
public void handleCreate(Book book) {
// why is this necessary?
book.getShelf().getBooks().add(book);
}

下面是实体类:

@Entity
public class Book {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

private String name;

@ManyToOne
private Shelf shelf;

public Shelf getShelf() {
return shelf;
}

public void setShelf(Shelf shelf) {
this.shelf = shelf;
}

public String getName() {
return name;
}

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

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.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;
Book other = (Book) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}

@Entity
public class Shelf {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

private String name;

@OneToMany
private List<Book> books = new ArrayList<Book>();

public List<Book> getBooks() {
return books;
}

public void setBooks(List<Book> books) {
this.books = books;
}

public String getName() {
return name;
}

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

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.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;
Shelf other = (Shelf) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}

}

我正在使用 Spring Boot 1.1.8。

最佳答案

在您的 Shelf 实体中,将 mappedBy = "self" 属性添加到 books 中的 @OneToMany 注释中:

@OneToMany(mappedBy = "self")
private List<Book> books = new ArrayList<Book>();

这将使用与 self 匹配的引用自动填充书籍列表。

关于spring-data-rest - 成功添加带有父引用的子实体后,子实体不显示在父资源下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26805228/

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