简体   繁体   中英

Getting error while sending foreign key in json in Springboot REST API?

I am making a simple application. It has two entities ie Book and Address. Book has author instance because they have one to one relationship. If I am sending author instance in with book it is working fine but When I am sending already exisiting author id I am getting Persistent Object Exception. Please help me.

@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 Response I am sending:

{ "title": "Hello Java", "author": { "id": 1 } }

Give complete author object in the JSON response instead of giving only his id like,

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

Do this, don't give author id then object with your required author name will get created.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM