gpt4 book ai didi

java - Spring boot REST api,在外键上传递 id 而不是整个对象

转载 作者:太空宇宙 更新时间:2023-11-04 09:49:32 25 4
gpt4 key购买 nike

我正在尝试使用 Spring boot 应用程序为 Web 和移动应用程序构建 REST API。在我的应用程序中,我有多个外键,并且我只想传递对象的 id 而不是整个对象。请参阅下面的示例。

模型书

// imports

@Entity
public class Book {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

private String title;
private String isbn;

@ManyToOne
@JoinColumn(name = "category_id", updatable = false)
private BookCategory bookCategory;

public Book() {
}

public Book(Integer id, String title, String isbn, BookCategory bookCategory) {
this.id = id;
this.title = title;
this.isbn = isbn;
this.bookCategory = bookCategory;
}

// getters and setters
}

型号类别

// imports

@Entity
public class BookCategory {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

private String name;

@OneToMany(mappedBy = "bookCategory", cascade = CascadeType.ALL)
private List<Book> books;

public BookCategory() {
}

public BookCategory(Integer id, String name) {
this.id = id;
this.name = name;
}

// getters and setters
}

图书 Controller

// imports

@RestController
@RequestMapping(path = "/api/v1")
public class BookController {

@Autowired
private BookRepository bookRepository;

// other methods for index, show, put and delete

@PostMapping(path = "/books")
public book createBook(@RequestBody Book book) {
return bookRepository.save(book);
}

}

图书存储库

// imports

public interface BookRepository extends PagingAndSortingRepository<Book, Integer> {
}

书籍类别已预先加载到数据库中,我不想允许客户更改它们或添加新类别。

这是我尝试过的 JSON POST 以及存储在数据库中的对象。

请求

{
"title": "Tirant lo blanc",
"isbn": "9788475841199",
"category_id": 4
}

回应

{
"title": "Tirant lo blanc",
"isbn": "9788475841199",
"bookCategory": null
}

我也尝试将其作为对象发送,但结果为空。

{
"title": "Tirant lo blanc",
"isbn": "9788475841199",
"category_id": {
"id": 4
}
}

如何发送类别 ID 以将书籍正确存储在数据库中?发送整个类别对象是否更好?我也尝试过,但是响应和数据库中存储的书籍始终处于类别 null。

最佳答案

如果您只想传递对象的 id,请设置您希望其返回的 getters

例如:

// imports

@Entity
public class Book {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

private String title;
private String isbn;

@ManyToOne
@JoinColumn(name = "category_id", updatable = false)
private BookCategory bookCategory;

public Book() {
}

public Book(Integer id, String title, String isbn, BookCategory bookCategory) {
this.id = id;
this.title = title;
this.isbn = isbn;
this.bookCategory = bookCategory;
}

// getters
public Integer getBookCategory() {
return bookCategory.getId();
}
}

关于java - Spring boot REST api,在外键上传递 id 而不是整个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54957864/

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