【问题标题】:Getting error while sending foreign key in json in Springboot REST API?在 Spring Boot REST API 中发送 json 中的外键时出错?
【发布时间】:2022-01-20 08:12:21
【问题描述】:

我正在制作一个简单的应用程序。它有两个实体,即书本和地址。书有作者实例,因为它们具有一对一的关系。如果我将作者实例与书籍一起发送,它工作正常,但是当我发送已经存在的作者 ID 时,我会收到持久对象异常。请帮帮我。

@Table(name = "books")
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String title;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "author_id",referencedColumnName = "id")
    private Author author;

    public Book(Long id,String title,Author author) {
        this.id = id;
        this.title = title;
        this.author = author;
    }}

@Entity
@Table(name = "authors")
public class Author {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String firstName;
    private String lastName;

    public Author(Long id, String firstName, String lastName) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }}


@Service
public class BookService {

    @Autowired
    private BookRepository repository;

    public List<Book> find() {
        return repository.findAll();
    }

    public Book find(Long id) {
        return repository.findById(id).get();
    }

    public Book save(Book book) {
        return repository.save(book);
    }
}

@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    @GetMapping
    public List<Book> find(){
        return bookService.find();
    }

    @GetMapping(path = "{id}")
    public Book find(@PathVariable Long id){
        return bookService.find(id);
    }

    @PostMapping
    public Book find(@RequestBody Book book){
        return bookService.save(book);
    }
}

我正在发送的 Json 响应:

{ "title" : "你好 Java", “作者” : { “身份证”:1 } }

【问题讨论】:

  • 一个作者可以拥有多本书对吧?或者对于您的应用程序,您具有这种一对一的关系
  • 我有一对一的关系。一位作者可以拥有一本书
  • 当我在 json 对象中发送新作者时它工作正常。但是如果我在 json 对象中发送已经存在的作者的 id,我会得到持续的异常
  • @TameerHussain 你能告诉我你的controllerserviceImpl吗?
  • 我已经更新了代码,请检查一下。

标签: java spring spring-boot hibernate spring-data-jpa


【解决方案1】:

在 JSON 响应中给出完整的作者对象,而不是只给出他的 id,

{ "title" : "Hello Java", "author" : { "firstName": "something", "lastName":"something"} }

这样做,不要提供作者 ID,然后将创建具有所需作者姓名的对象。

【讨论】:

  • 你的回答报错detached entity passed to persist: com.rest.RestApiPojo.Entity.Author; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.rest.RestApiPojo.Entity.Author
  • 在有人反对之前编辑或删除它
猜你喜欢
  • 1970-01-01
  • 2020-11-26
  • 1970-01-01
  • 2019-04-17
  • 2019-03-26
  • 1970-01-01
  • 2020-08-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多