標籤:
hibernate 3.6.0的使用記錄
1.首先下載hibernate的開發jar包
2.引入jar包到項目中
(可以自己手動添加到項目的lib檔案夾在構建路徑 也可以通過IED來直接引入)
關鍵的jar包:
①hibernate的核心包
②hibernate解壓後lib檔案夾下required檔案夾下所有的jar包
③hibernate解壓後lib檔案夾下jpa檔案夾下的jar包
④資料庫驅動jar包
3.建立映射對象類以及所對應的(*.hbm.xml)檔案
4.在src目錄下建立hibernate.cfg.xml主設定檔(項目發布時會自動發布到WEB-INF目錄中的class檔案下)
在hibernate.cfg.xml中加入串連資料庫的相關配置一般有以下幾項:
<hibernate-configuration> <session-factory> <property name="connection.driver_class">com.mysql.jdbc.Driver</property><!--驅動--> <property name="connection.url">jdbc:mysql://127.0.0.1:3306/struts2andhibernate</property><!--url--> <property name="connection.username">root</property><!--資料庫使用者名稱--> <property name="connection.password">root</property><!--資料庫密碼--> <property name="dialect">org.hibernate.dialect.MySQLDialect</property><!--資料庫方言--> <property name="show_sql">true</property> <!-- 在後台列印sql語句,開發的時候設為true--> <property name="format_sql">true</property><!-- 將後台列印的sql語句格式化--> <property name="hbm2ddl.auto">update</property> <!--自動建表設定的-->
<!--引入相應的*.hbm.xml對應檔--> <mapping resource="entity/Users.hbm.xml"/> <mapping resource="entity/Students.hbm.xml"/> </session-factory></hibernate-configuration>
5 最後進行簡單的測試
測試和使用的關鍵步驟:
//獲得載入設定檔的管理類對象Configuration config = new Configuration();config.configure("cn/config/hibernate.cfg.xml")//預設載入src/hibernate.cfg.xml//建立session的工廠對象SessionFactory sf=config.buildSessionFactory();//建立session(代表一個會話,與資料庫連接的會話)Session session=sf.openSession();//開啟事務Transaction tx=session.beginTransaction();//儲存-資料庫session.save();//提交事務tx.commit();//關閉session.close();sf.close();
hibernate 4以上的相應用法//獲得載入設定檔的管理類對象Configuration config = new Configuration();config.configure("設定檔所在的路徑"); //不填寫預設是在src目錄下//獲得服務註冊對象ServiceRegistry servletRegistry = new ServiceRegistryBuilder() .applySettings(config.getProperties()).buildServiceRegistry();//獲得sessionFactory對象SessionFactory sessionFactory = config.buildSessionFactory(servletRegistry);//獲得session對象,建立會話 兩種方法//方法一:
Session session = sessionFactory.openSession();//方法二:
Session session = sessionFactory.getCurrentSession();//在配置文檔中要進行相應的配置否則會拋出異常(添加一個屬性)<property name="hibernate.current_session_context_class">thread</property>這兩種建立session 的區別:1.getCurrentSession在事務提交或者復原之後會自動關閉,而opensession需要你手動關閉。如果使用openSession而沒有手動關閉,多次之後會導致串連池溢出2.openSession每次建立新的session對象,getCurrentSession使用現有的session對象
hibernate的簡單運用步驟筆記