1

I am trying to insert data into book table by reading data from a txt file, problem is only 1 insert query is generated at the commit() statement

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class BookClientFile {

public static void main(String[] args) {

    SessionFactory sf = new Configuration().configure().buildSessionFactory();
    Session s1 = sf.openSession();

    BufferedReader br = null;
    Transaction trans = null;

    try {
           br = new BufferedReader(new FileReader(new File("Books.txt")));
           String line = null;
           String [] row = null;
           Book bk = null;

           trans = s1.beginTransaction();
           while((line = br.readLine()) != null) {

               bk = new Book();
               row = line.split(",");

               bk.setBookId(Integer.parseInt(row[0].trim()));
               bk.setTitle(row[1].trim());
               bk.setAuthor(row[2].trim());

               s1.save(bk);
               trans.commit();
           }

    } catch(IOException e) {
        e.printStackTrace();
    }
    finally {

        s1.flush();
        s1.close();

    try {

        if(br != null) {

            br.close();
            br = null;
        }

    } catch(IOException e) {
        e.printStackTrace();
    }
    }
}
}
1
  • Don't you need to commit outside the while loop? Commented Jan 28, 2015 at 9:01

2 Answers 2

1

Swap the to lines to start transaction for each book.

       trans = s1.beginTransaction();
       while((line = br.readLine()) != null) {

Or move trans.commit(); out of the while

Sign up to request clarification or add additional context in comments.

1 Comment

same output, the programs halts after generating one sql query.
0

Take trans.commit(); out of the while loop.

1 Comment

nothing is happening , same output Hibernate: insert into Book (book_title, book_author, book_id) values (?, ?, ?)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.