一、批量插入

 1 @Test
 2     public void saveAll(){
 3 
 4         SessionFactory sessionFactory = getSessionFactory();
 5         Session session = sessionFactory.openSession();
 6         Transaction transaction = session.beginTransaction();
 7 
 8         //hibernate 没有insert语句,只能insert into 表名(字段名) select数据 ,   但是可以:
 9         // 1.save对象
10         // 2.借助update语句
11         // 3.借助sql语句
12 
13         //这里写一个借助update的demo
14         //先改再增
15         String hql = " update HTeacherEntity set tname = :a1 where tid = 1";
16         for (int i = 0; i < 10; i++) {
17 
18             session.createQuery(hql).setParameter("a1","老师老师"+i).executeUpdate();
19             session.createQuery("insert into HTeacherEntity(tname) select tname " +
20                     "from HTeacherEntity ht2 where ht2.tid = 1").executeUpdate();
21         }
22         //这种批量增相较于save对象方式减少了多次新建对象,提高了开发效率,
23         // 但是每一条数据的新增都要走一条修改语句,其实也增加了数据库负担
24         commit(transaction,sessionFactory,session);
25     }

二、批量删除

 1 @Test
 2     public void testDeleteAll(){
 3 
 4         SessionFactory sessionFactory = getSessionFactory();
 5         Session session = sessionFactory.openSession();
 6         Transaction transaction = session.beginTransaction();
 7 
 8         //删除时要注意,有的数据有外键约束,要结合业务需求来操作
 9         String hql = " delete from HStudentEntity s where s.sname like :tname";
10         //增删改一般都是executeUpdate 查询用list
11         session.createQuery(hql).setParameter("tname", "%学生%").executeUpdate();
12 
13         //不要忘记提交事务
14         commit(transaction,sessionFactory,session);
15     }

三、批量修改

 1 @Test
 2     public void updateAll(){
 3 
 4         SessionFactory sessionFactory = getSessionFactory();
 5         Session session = sessionFactory.openSession();
 6         Transaction transaction = session.beginTransaction();
 7 
 8         String hql = " update HTeacherEntity t set t.tname = :pl where t.tid > :minId";
 9         //增删改一般都是executeUpdate 查询用list
10         session.createQuery(hql).setParameter("pl", "批量").setParameter("minId",0).executeUpdate();
11 
12         //不要忘记提交事务
13         commit(transaction,sessionFactory,session);
14     }