1、使用session的save方法进行插入
1 public void saveUser(User user){ 2 3 Session session = null; 4 Transaction transaction = null; 5 try { 6 session = HibernateUtils.getSession(); 7 transaction =session.beginTransaction(); 8 /*保存对象到数据库*/ 9 session.save(user); 10 session.flush(); 11 transaction.commit(); 12 }catch (HibernateException e){/*catch可省略,数据库收不到提交会自动回滚*/ 13 if (transaction != null){ 14 transaction.rollback(); 15 throw e; 16 } 17 }finally { 18 if (session != null){ 19 session.close(); 20 } 21 } 22 }