【发布时间】: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 你能告诉我你的
controller或serviceImpl吗? -
我已经更新了代码,请检查一下。
标签: java spring spring-boot hibernate spring-data-jpa