hibernate批量插入数据库操作案例


public void testSave1() {
               Session session = null;
               Transaction tx = null;
               try {
                       session = HibernateUtils.getSession();
                       tx = session.beginTransaction();
                       User1 user = new User1();
                       user.setName("李四");

                        //主键采用数据库序列自动生成策略
                       session.save(user);

                        /*flush()和缓存相关。执行时会清除session缓存并向数据库发送SQL语句并执行,但此时如果数据库当前    存 在一个事务,数据库会先将这些SQL语句缓存起来,那么此时在数据库中是无法看到SQL语句执行结果的。除非执行commit提交了事务。只要没有执行commit()方法,就能通过rollback()方法进行回滚*/
                       session.flush();

                       /*提交事务,默认情况下commit操作会先执行flush清理缓存,所以不用显示的调用flush,commit后数据是无法 回滚的*/
                       tx.commit();
               } catch (Exception e) {
                       e.printStackTrace();
                       tx.rollback();
               } finally {
                       HibernateUtils.closeSession(session);
               }
       }

你可能感兴趣的:(hibernate批量插入数据库操作案例)