I am using OneToMany relationship in spring data Jpa and testing the api using postMan
@Entity
@Table(name = "book_category")
public class BookCategory {
ParentEntity
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "bookCat_id")
private Long id;
private String name;
@OneToMany(cascade = CascadeType.ALL, mappedBy="bookCategory")
private Set<Book> books;
public BookCategory(String name, Set<Book> books) {
this.name = name;
this.books = books;
}
// getter and setter
}
ChildEntity
@Entity
@Table(name = "book")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "book_id")
private Long bookId;
private String name;
@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "bookCat_id")
BookCategory bookCategory;
public Book() {
}
//getter and Setter
}
ControllerClass
@RestController
@RequestMapping(value = "/bookCategory")
public class BookController {
@Autowired
BookCategoryRepository bookCategoryRepository;
@Autowired
BookRepository bookRepository;
@PostMapping("/addBookCategory")
public BookCategory savePerson(@Valid @RequestBody BookCategory bookCategory){
return bookCategoryRepository.save(bookCategory);
}
}
calling Rest Api from postman and passing json as
{
"name":"Category 1",
"books":[
{"name" : "Hello Koding 1"},
{"name":"Hello Koding 2"}
]
}
Following Query is executing by hibernate query is also correct while i am calling rest point the thing Hibernate: insert into book_category (name) values (?) Hibernate: insert into book (book_cat_id, name) values (?, ?)
it is not inserting book_cat_id, in book_cat_id it is passing null so null is getting store
Data stored in database book_category Parent Table in database
book(ChildTable) book(ChildTable) I want to get Child Table Like I want my table like this