简体   繁体   中英

Save child objects in order using Jpa Repository

I have the one-to-many relation between Parent (Book) and Child (Page) tables. In the parent object I have a

@OneToMany(cascade = CascadeType.ALL, mappedBy = "book", orphanRemoval = true)
private List<Page> pages = new ArrayList<>();

So, I want to duplicate the book. I create new Book object and add all pages from the book which should be duplicated to new book in cycle using method

public void addPage(Page page) {
    pages.add(page);
}

Also I have BookRepository (extends JpaRepository). Then I tried

bookRepository.save(newBook)

The problem is that all pages are saved in chaotic order ID, eg 1st page has ID 34, 2nd page has ID 22, 3rd page has ID 27 etc. (but I added pages in newBook in order - 1, 2, 3, 4 .....) How can I fix it and make the pages with sequential IDs in db (eg 1st page should have ID 1, 2nd page should have ID 2 etc.)?

With JPA2 you can use the annotation @OrderColumn to specify a column in your database table, which is used for the ordering. If you update your database manually, you have to add that column to your table and init it with the wanted order of the pages.

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