When storing values using JPA, how to assign a key value to a class field mapped to @AnyToOne (see Foreign Key)

Asked 2 years ago, Updated 2 years ago, 114 views

EntityTo establish a relationship inside, we mapped it using the @AnyToOne annotation. For example:

@Entity
public class Book {
    @Id
    @GeneratedValue
    private long id;

    @Column
    private String name;

    @ManyToOne(fetch = FetchType.LAZY)
    private Publisher publisher

    // // getter & setter
}

@Entity
public class Publisher {
    @Id
    @GeneratedValue
    private long id;

    @Column
    private String name;

    // // getter & setter
}

In order to store the value of publisher when each generated table name is book, publisher and PK(=id) is 1, we tried to deliver the JONSODE as follows.

Controller:

@PutMapping(value = "/books")
public ResponseEntity createBook(@RequestBody Book book) {
    bookRepository.save(book);

    // Omitted
}

the body of the request :

{
  "name" : "jpa in action",
  "publisher" : "1"
}

I roughly summarized the contents and wrote it. The problem is that if you pass the body of the request as shown above, the Publisher entity does not have a constructor with a single numeric type parameter and cannot process the request.

Is there a way to inquire and store the value automatically referenced by passing PK (=id) in the body of the request, just as PK (=id) using a pre-implemented function such as FindOne? Or in the logic above, should I take a separate PK(=id) value as a field, look up Publisher directly, and manually work on Book object like

The actual database table contains a value of Foreign Key which would be publisher_id in the above situation. Therefore, even if "publisher_id" : 1, was added to the request body, the value was not saved in the publisher_id column of the actual table. What should I do?

jpa hibernate spring-boot spring-data-jpa spring-data

2022-09-22 11:59

1 Answers

When you save it, you have to do it with several strategies. according to the nature of one's work Decide which policy you want to take the cascade policy first.

Before saving by default in JPA, search for findOne to determine whether to update or save new content.


2022-09-22 11:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.