简体   繁体   中英

How to tell Hibernate to retrieve the id instead of inserting a new record

My question may be dumb to some people, but I can't tell Hibernate to retrieve an ID instead of inserting a new record. My problem is with the POST method of Spring Boot. For example, let's imagine that I have 3 tables: authors, books, and book types.

I send a JSON like this one to insert my new book (relationships are configured with CascasdeType.ALL ) :

{
  "book": {
    "name": "my super book",
    "author": [
      {
        "name": "Julian DESD"
      },
      {
        "name": "Maria GRATH"
      }
    ],
    "type" : {
       "name": "Fantasy"
  }
}

In my Book Type table, the Fantasy type already exists. I would like hibernate to get this ID instead of inserting a new "Fantasy" record with a new ID (which triggers errors due to uniqueness constraints).

Book.java

public class Book implements Serializable {

    // Other fields 

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "BookType_idBookType")
    private BookType type;
}

BookController.java

@PostMapping("/add")
public ResponseEntity<Void> addBook(@RequestBody Book book) {
   Book book1 = bookService.save(book);
   URI location = ServletUriComponentsBuilder
          .fromCurrentRequest()
          .path("/{id}")
          .buildAndExpand(book1.getId())
          .toUri();
   return ResponseEntity.created(location).build();
}

I'm probably missing an annotation. Please help me.

Its based on primary key you defined in the hibernate entity class. 1)If Primary key generation strategy is auto then you have to write code to fetch record then update the records 2)If Primary key is name then it will insert/update the records based on the availability in the database

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