-
Jan 13th, 2009, 04:02 PM
#1
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
-
Jan 14th, 2009, 01:00 AM
#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?!
-
Jan 14th, 2009, 09:51 AM
#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?
-
Jan 15th, 2009, 06:43 AM
#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
kashefbasher@gmail.com
-
Nov 21st, 2011, 08:16 AM
#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);
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules