hibernate批量处理数据
(1)使用HQL进行批量操作 数据库层面 executeUpdate()
@Test
public void test2() {
Query query = session.createQuery("insert into Stu(sname) select s.sname from Stu s");
query.executeUpdate();
}
@Test
public void test3() {
Query query = session.createQuery("update Stu set sname='学生1' where sid>2");
query.executeUpdate();
}
(2)使用JDBC API进行批量操作 数据库层面
@Test
public void test4() {
Work work = new Work() {
public void execute(Connection connection) throws SQLException {
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM Stu1");
while (resultSet.next()) {
System.out.println(resultSet.getString("sname"));
}
}
};
session.doWork(work);
}
(3)使用Session进行批量操作 会进缓存
@Test
public void test5() {
for (int i = 0; i < 100; i++) {
Stu stu = new Stu();
stu.setSname("学员2222");
session.save(stu);
if (i % 30 == 0) {
session.flush();
session.clear();
}
}
}