6

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

1 Answers1

4

The problem is that you are not setting parent in child object. Somewhere in the code you should call the

public void setBookCategory(BookCategory bookCategory) { ... }

method of the Book entity.

I'd suggest to resolve this issue by using DTOs in controller and mapping them to entities in service layer, as using peristent entities as parameters of http requests can lead to serious security vulnerabilities as explained here.

EDIT: Alternatively, even thought I would not encourage this solution would be to modify the savePerson method like this

@PostMapping("/addBookCategory")
public BookCategory savePerson(@Valid @RequestBody BookCategory bookCategory){
    bookCategory.getBooks().forEach(book -> book.setBookCategory(bookCategory));
    return bookCategoryRepository.save(bookCategory);
}
toucheqt
  • 725
  • 2
  • 8
  • 15
  • public void setBookCategory(BookCategory bookCategory) { ... } this is part of getter/setter Following Query is executing 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 – abhinash pandey Sep 05 '19 at 05:09
  • Hibernate is inserting null values in book_cat_id because the setBookCategory method is implemented, but never called. Put a breakpoint in the savePerson method, you will find out that the Books in the BookCategory do not have a parent (BookCategory in Book entities will be null). – toucheqt Sep 05 '19 at 06:02
  • Then What is the solution for it – abhinash pandey Sep 05 '19 at 16:49
  • Data is saved in db but is gitving error like this "status":200,"error":"OK","message":"Could not write JSON: Infinite recursion (StackOverflowError); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: com.abhinash.restapi.entities.OneToMany.BookCategory[\"books\"] AND Can you tell why i am getting this error *** java.lang.instrument ASSERTION FAILED ***: "!errorOutstanding" with message transform method call failed at JPLISAgent.c line: 844 – abhinash pandey Sep 05 '19 at 18:06
  • @Abhinash I can point you out to right direction - https://stackoverflow.com/a/18288939/3750108 there is a solution to the problem you are now facing. – toucheqt Sep 05 '19 at 18:49