1.批量插入
private void addUsers()
throws Exception{
Session session = HibernateUtil.currentSession();
Transaction tx = session.beginTransaction();
for(
int i =
0;i <
10000;i++){
User u1 =
new User();
u1.setName(
"xxxx" + i);
u1.setAge(i);
session.save(u1);
if(i %
20 ==
0){
session.flush();
session.clear();
}
}
tx.commit();
HibernateUtil.closeSession();
}
上面的代码中当i % 20 == 0 时,手动将Session缓存的数据写入数据,并且清空Session缓存里的数据。除了要对Session级别的缓存进行处理外,还应该通过配置来关闭SessionFactory的二级缓存。
2.批量更新
` private void updateUsers() throws Exception{
Session session = HibernateUtil
.currentSession()
Transaction tx = session
.beginTransaction()
//查询出User表中的所有记录
ScrollableResults users = session
.createQuery(
"from User")
.setCacheMode(CacheMode
.IGNORE)
.scroll(ScrollMode
.FORWARD_ONLY)
int count =
0
while(users
.next()){
User u = (User)users
.get(
0)
u
.setName(
"新用户名" + count)
if(++count %
20 ==
0){
session
.flush()
session
.clear()
}
}
tx
.commit()
HibernateUtil
.closeSession()
}
3.DML风格的批量更新/删除
Hibernate提供的HQL语句也支持批量update和delete语法。 批量update和delete语句的语法格式如下:
update | delete from? <ClassName> [where where_conditions]
String hql =
"update User u set name = :newName"
int updatedEntities = session
.createQuery(hql)
.setString(
"newName",
"新名字")
.executeUpdate()