使用Hibernate操作數據庫需要七個步驟:
(1)讀取并解析配置文件
Configuration conf = newConfiguration().configure();
(2)讀取并解析映射信息,創建SessionFactory
SessionFactory sf = conf.buildSessionFactory();
(3)打開Session
Session session = sf.openSession();
(4)開始一個事務(增刪改操作必須,查詢操作可選)
Transaction tx = session.beginTransaction();
(5)數據庫操作
session.save(user);//或其它操作
(6)提交事務(回滾事務)
tx.commit();(tx.rollback();
(7)關閉session
session.close();
注:如果Hibernate 配置文件中,current_session_context_class 參數設置為thread 并采用SessionFactory 的getCurrentSession()方法獲的Session 實例則不需要此步。
如圖所示: