Announcement Announcement Module
Collapse
No announcement yet.
How to insert multiple rows in a table by using hibernate Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to insert multiple rows in a table by using hibernate

    I have a table called book_chapter.It contains book_id and chapter_id as columns.
    I have mapped this table to an entity called BookChapter.
    Book and Chapter relationship is coming from GUI.
    One book may have many chapters.I have to insert all the rows coming from GUI into book_chapter table.
    One way of doing this is to insert one - by one as below :-

    BookChapter bc = new BookChapter() ;
    bc.setBookId(bookId1) ;
    bc.setChapterId(chapterId1) ;
    session.save(bc) ;

    bc=new BookChapter() ;
    bc.setBookId(bookId2) ;
    bc.setChapterId(chapterId2) ;
    session.save(bc) ;

    and so on.........

    Is there any way I can do this by writing save method only once?
    I am looking for something like this :-
    List<BookChapter> bookChapterList = new ArrayList<BookChapter>() ;
    BookChapter bc1 = new BookChapter() ;
    bc.setBookId(bookId1) ;
    bc.setChapterId(chapterId1) ;
    bookChapterList.add(bc1) ;

    BookChapter bc2 = new BookChapter() ;
    bc2.setBookId(bookId2) ;
    bc2.setChapterId(chapterId2) ;
    bookChapterList.add(bc2) ;

    session.save(bookChapterList) ;

    I tried passing List object to save method as above but it does not work.Does anyone know of any utility method which does this sort of thing?

    Thanks

  • #2
    Please use [ code][/code ] tags when posting code.

    Your approach seems wrong, shouldn't you have a Book object and add Chapter to a Book and then save/update the Book?!

    Comment


    • #3
      Yes.I don't have the Chapter object.I only have BookChapter object which maps to Book_Chapter table in db schema.
      I don't have any Book table or Chapter table.
      Is there any solution for the problem I have?

      Comment


      • #4
        saveOrUpdateAll(Collection entities)

        if you can use hibernateTemplate instead of session then you can save your object list by using saveOrUpdateAll(Collection entities).

        Kashif Bashir

        [email protected]

        Comment


        • #5
          when you map one to many relationship tables, in the father-table you should have the object of the other table as usual is the same name followed by an 's' meaning that is plural, remember is a one to MANY so in the BOOK object you should have the hash for BOOKCHAPTER called bookchapters then you just add your objects to that list something like this: book.setBookChapters(object);

          Comment

          Working...
          X