我试图通过读取txt文件中的数据将数据插入到book表中,问题只是在commit()
语句中生成了1个插入查询
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();
}
}
}
}
答案 0 :(得分:1)
交换行以开始每本书的交易。
trans = s1.beginTransaction();
while((line = br.readLine()) != null) {
或者暂时移动trans.commit();
答案 1 :(得分:0)
将trans.commit();
从while循环中取出。