Hibernate Util簡單討論
本文向大家介紹Hibernate Util,可能好多人還不了解Hibernate Util,沒有關(guān)系,看完本文你肯定有不少收獲,希望本文能教會你更多東西。
Hibernate提供了許多不同的方式來配置該框架,包括程序方面的配置。上述代碼設(shè)置了連接池。注意,使用HSQLDB的內(nèi)存數(shù)據(jù)庫需要用戶名'sa’。還樣要確保指定一個空格作為口令。為了啟動Hibernate的自動模式生成功能,需設(shè)置hibernate.hbm2ddl.auto屬性為’creat-drop’。
實際測試 我的項目是處理將大量的棒球數(shù)據(jù),所以我添加了四個進(jìn)行映射的類(Player、PintchingStint、,BattingSint和FieldStint)。***創(chuàng)建Hibernate的會話工廠,并將其插入Hibernate Util類,該類只為Hibernate會話的整個應(yīng)用程序提供一個訪問方法。Hibernate Util的代碼如下:
- import org.hibernate.*;
- import org.hibernate.cfg.Configuration;
- public class HibernateUtil {
- private static SessionFactory factory;
- public static synchronized Session getSession() {
- if (factory == null) {
- factory = new Configuration().configure().buildSessionFactory();
- }
- return factory.openSession();
- }
- public static void setSessionFactory(SessionFactory factory) {
- HibernateUtil.factory = factory;
- }
- }
因為所有代碼(經(jīng)過單元測試的產(chǎn)品級代碼)都是從Hibernate Util獲取Hibernate會話,所以能在同一個位置對其進(jìn)行配置。為了對代碼的***位進(jìn)行單元測試而訪問TestSchema類將會激活靜態(tài)初始化程序,該程序?qū)惭bHibernate并且將測試SessionFactory插入到Hibernate Util中。對于產(chǎn)品級代碼,可以使用標(biāo)準(zhǔn)hibernate.cfg.xml配置機(jī)制來初始化 SessionFactory。
那么單元測試中的外部特征是什么?下面的測試代碼片段是用來檢查邏輯的,決定運(yùn)動員在棒球聯(lián)盟比賽中是哪個位置的人選:
- public void testGetEligiblePositions() throws Exception {
- Player player = new Player("playerId");
- TestSchema.addPlayer(player);
- FieldingStint stint1 = new FieldingStint("playerId", 2004, "SEA", Position.CATCHER);
- stint1.setGames(20);
- TestSchema.addFieldingStint(stint1);
- Set positions = player.getEligiblePositions(2004);
- assertEquals(1, positions.size());
- assertTrue(positions.contains(Position.CATCHER));
- }
【編輯推薦】