Hibernate入门(二)——hibernateAPI详解
Hibernate API 詳解
1.Configuration
功能:配置加載類,用于加載主配置,orm元數據加載
.創建:
Configuration conf = new Configuration();讀取指定配置文件(加載主配置文件,即我們經常創建的"hibernate.cfg.xml")
從下圖中可以發現有很多關于讀取方法的重載。。。
雖然有這么多重載,但是一般咱就用無參構造方法把,默認找到src下的hibernate.cfg.xml文件
conf.configure();
當然可以在創建Configuration對象的時候直接執行:
Configuration conf = new Configuration().configure();
它們的源碼如下:
2.SessionFactory
功能:用于創建數據庫核心對象session對象的工廠,簡單的說,功能就只有一個-------------------創建session對象
注意:
1.sessionFactory負責保存和使用所有配置信息,消耗內存非常大
2.sessionFactory屬于線程安全的對象設計(不同的用戶對應不同的session)
結論:保證在web項目中,只創建一個sessionFactory
讀取完主配置文件(hibernate.cfg.xml)后自然要拿到SessionFactory
SessionFactory sf = conf.buildSessionFactory();?
3.session對象
創建:
? ①:一個新的session對象
Session session = sf.openSession();②:獲得一個與線程綁定的session對象
Session cSession = sf.getCurrentSession();①插入
注意:
增刪改查操作之前要開啟事務,結束后要提交事務
最后要session釋放資源(后面的操作我就不完整寫了)
拿到對象,直接用save方法就行了
Transaction tx = session.beginTransaction();Customer customer = new Customer();customer.setCust_id(2);customer.setCust_name("測試");session.save(customer);tx.commit();
session.close();
②根據主鍵查詢
Customer customer = session.get(Customer.class, 2);③修改
拿到對象然后調用update方法()
Customer customer = session.get(Customer.class, 2); customer.setCust_name("測試2"); session.update(customer);發現一個"插入或者修改"
?
④刪除
首先拿到對象,然后調用delete()
Customer customer = session.get(Customer.class, 2); session.delete(customer);?
4.自定義Hibernate工具類
對于SessionFactory,提到最好只創建一個,其次就是封裝重復代碼,提高代碼的復用性
package deep.utils;import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration;/*** Hibernate工具類* @author DeepSleeping**/ public class HibernateUtils {private static SessionFactory sessionFactory;static{Configuration conf = new Configuration().configure();sessionFactory = conf.buildSessionFactory();}public static Session getSession(){return sessionFactory.openSession();}public static Session getCurrentSession(){return sessionFactory.getCurrentSession();} }?
?
轉載于:https://www.cnblogs.com/deepSleeping/p/9774757.html
總結
以上是生活随笔為你收集整理的Hibernate入门(二)——hibernateAPI详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 最新Java校招面试题及答案
- 下一篇: 02-模板字符串