通过HQL来进行批量操作 1. 批量更新语句 Session session=sessionFactory.openSession(); Transaction tx=session.beginTransaction(); String hqlUpdate="update Customer c set c.name =:newName where c.name =:oldName"; Int updateEntitys=session.createQuery(hqlUpdate) .setString("newName","Mike") .setString("oldName","Tom") .executeUpdate(); Tx.commit(); Session.close(); 以上程序代码向数据库发送的SQL语句为: Updae CUSTOMERS set NAME="Mike" where NAME="Tom" 批量删除数据 Session的delete()方法一次只能删除一个对象,不适合进行批量删除操作。 Session session=sessionFactory.openSession(); Transaction tx=session.beginTransaction(); String hqlDelete="delete Customer c where c.name =:oldName"; Int deleteEntities=session.createQuery(hqlDelete) .setString("oldName","Tom") .executeUpdate (); Tx.commit() Session.close(); 以上那个程序向数据库提交的sql语句为: Delete from CUSTOMERS where NAME="Tom" 批量插入数据 插入数据库的SQL语法为: Insert into EntityName properties_list select_statement 以上entityName表示持久化类的名字,properties_list表示持久化类的属性列表,select_statment表示子查询语句。以下代码能把CUSTOMERS表中的数据复制到DELINQUENT_ACCOUNTS表中: Session session=sessionFactory.openSession(); Transaction tx=session.beginTransaction(); String hqlInsert="insert into DelinquentAccount(id,name) select c.id,c.name from Customer c where c.ic>1"; Int createEntities=session.createQuery(hqlInsert) .executeUpdate(); Tx.commit(); Session.close(); 以上程序代码向数据库发送的SQL语句为: Insert into DELINQUENT_ACCOUNTS(ID,NAME) select ID, NAME from CUSTOMERS where ID>1
通过HQL来进行批量操作
最新推荐文章于 2021-05-20 14:50:05 发布