Hibernate中幾個xml檔案的說明
阿新 • • 發佈:2019-01-22
在hibernate中我們常見的幾個xml檔案是hibernate.cfg.xml和xx.hbm.xml檔案(xx是代名詞,根據資料庫表的不同有所不同)。hibernate.cfg.xml檔案中配置了資料庫的連線的有關引數包括要連線的資料庫,連線資料庫所需要的驅動,登陸資料庫的使用者名稱和密碼。這些都是寫在<property></property>標籤內的
還有最重要的一點就是定義的關係資料庫中表與物件對映的檔案例如
<mapping resource="onlyfun/caterpillar/User.hbm.xml"/>
對映檔案User.hbm.xml定義了程式中的物件與資料庫中表的對映關係,物件中成員變數與資料庫中欄位的對應。
持久化流程是 SessionFacory根據hibernate.cfg.xml檔案建立一個SessionFactory然後由SessionFactory建立一個Session然後持久化操作就交給Session來處理,完成後關閉Session。
例如
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx= session.beginTransaction();
session.save(user);
tx.commit();
session.close();
sessionFactory.close();
上邊Transaction為事務處理,以便保持多個數據庫操作的一致性。