Hibernate使軟件適應不同的數據庫易如反掌

                對于一個通用型的軟件來說,有的客戶喜歡MySQL,有的客戶則已經購買了Oracle,還有些客戶已經習慣了SQLServer,因此軟件要面對的后臺數據庫類型可能是多種多樣的。如果為了讓軟件能適應各種數據庫,而開發一連串針對不同數據庫的軟件版本,對于開發和維護都是一場噩夢,幸好我們有了Hibernate。下面我通過一個簡單的小例子來表明Hibernate對于開發適應不同數據庫的軟件是多么的易如反掌。
          程序結構圖

          源代碼
          db.HibernateUtil
          package db;

          import net.sf.hibernate.HibernateException;
          import net.sf.hibernate.Session;
          import net.sf.hibernate.cfg.Configuration;
          import net.sf.hibernate.SessionFactory;

          /**
           * Configures and provides access to Hibernate sessions, tied to the
           * current thread of execution.  Follows the Thread Local Session
           * pattern, see {
          @link http://hibernate.org/42.html}.
           
          */

          public class HibernateUtil {

              
          /** 
               * Location of hibernate.cfg.xml file.
               * NOTICE: Location should be on the classpath as Hibernate uses
               * #resourceAsStream style lookup for its configuration file. That
               * is place the config file in a Java package - the default location
               * is the default Java package.<br><br>
               * Defaults: <br>
               * <code>CONFIG_FILE_LOCATION = "/hibernate.conf.xml"</code> 
               * You can change location with setConfigFile method
               * session will be rebuilded after change of config file
               
          */

              
          private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
              
          private static final ThreadLocal threadLocal = new ThreadLocal();
              
          private  static Configuration configuration = new Configuration();
              
          private static SessionFactory sessionFactory;
              
          private static String configFile = CONFIG_FILE_LOCATION;

              
          private HibernateUtil() {
              }

              
              
          /**
               * Returns the ThreadLocal Session instance.  Lazy initialize
               * the <code>SessionFactory</code> if needed.
               *
               *  
          @return Session
               *  
          @throws HibernateException
               
          */

              
          public static Session getCurrentSession() throws HibernateException {
                  Session session 
          = (Session) threadLocal.get();

                  
          if (session == null || !session.isOpen()) {
                      
          if (sessionFactory == null{
                          rebuildSessionFactory();
                      }

                      session 
          = (sessionFactory != null? sessionFactory.openSession()
                              : 
          null;
                      threadLocal.set(session);
                  }


                  
          return session;
              }


              
          /**
               *  Rebuild hibernate session factory
               *
               
          */

              
          public static void rebuildSessionFactory() {
                  
          try {
                      configuration.configure(configFile);
                      sessionFactory 
          = configuration.buildSessionFactory();
                  }
           catch (Exception e) {
                      System.err
                              .println(
          "%%%% Error Creating SessionFactory %%%%");
                      e.printStackTrace();
                  }

              }


              
          /**
               *  Close the single hibernate session instance.
               *
               *  
          @throws HibernateException
               
          */

              
          public static void closeCurrentSession() throws HibernateException {
                  Session session 
          = (Session) threadLocal.get();
                  threadLocal.set(
          null);

                  
          if (session != null{
                      session.close();
                  }

              }


              
          /**
               *  return session factory
               *
               
          */

              
          public static SessionFactory getSessionFactory() {
                  
          return sessionFactory;
              }


              
          /**
               *  return session factory
               *
               *    session factory will be rebuilded in the next call
               
          */

              
          public static void setConfigFile(String configFile) {
                  HibernateUtil.configFile 
          = configFile;
                  sessionFactory 
          = null;
              }


              
          /**
               *  return hibernate configuration
               *
               
          */

              
          public static Configuration getConfiguration() {
                  
          return configuration;
              }


          }
          model.User
          package model;

          public class User
          {
              
          private int id;

              
          private String username;

              
          private String password;

              
          public int getId()
              
          {
                  
          return id;
              }


              
          public void setId(int id)
              
          {
                  
          this.id = id;
              }


              
          public String getPassword()
              
          {
                  
          return password;
              }


              
          public void setPassword(String password)
              
          {
                  
          this.password = password;
              }


              
          public String getUsername()
              
          {
                  
          return username;
              }


              
          public void setUsername(String username)
              
          {
                  
          this.username = username;
              }

          }

          model.hbm.xml
          <?xml version='1.0' encoding='UTF-8'?>
          <!DOCTYPE hibernate-mapping PUBLIC
                    "-//Hibernate/Hibernate mapping DTD 2.0//EN"
                    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"
          >
          <hibernate-mapping>
          <class name="model.User" table="user1" >
          <id name="id">
          <generator class="identity"/>
          </id>
          <property name="username"/>
          <property name="password"/>
          </class>
          </hibernate-mapping>
          hibernate.cfg.xml
          <?xml version='1.0' encoding='UTF-8'?>
          <!DOCTYPE hibernate-configuration PUBLIC
                    "-//Hibernate/Hibernate Configuration DTD 2.0//EN"
                    "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd"
          >

          <!-- Generated by MyEclipse Hibernate Tools.                   -->
          <hibernate-configuration>

          <session-factory>
              
          <property name="dialect">net.sf.hibernate.dialect.SQLServerDialect</property>
              
          <property name="connection.url">jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=login</property>
              
          <property name="connection.username">lzqdiy</property>
              
          <property name="connection.password">lzqdiy</property>
              
          <property name="connection.driver_class">com.microsoft.jdbc.sqlserver.SQLServerDriver</property>
              
          <property name="myeclipse.connection.profile">conn2</property>
              
          <mapping resource="model/model.hbm.xml" />
          </session-factory>

          </hibernate-configuration>
          HibernateTest
          import java.util.List;
          import model.User;
          import net.sf.hibernate.HibernateException;
          import net.sf.hibernate.Query;
          import net.sf.hibernate.Session;
          import net.sf.hibernate.Transaction;
          import db.HibernateUtil;

          public class HibernateTest
          {

              
          /**
               * 
          @param args
               * 
          @throws HibernateException
               
          */

              
          public void insertUser() throws HibernateException
              
          {
                  Session session 
          = HibernateUtil.getCurrentSession();
                  Transaction tx 
          = session.beginTransaction();
                  User user 
          = new User();
                  user.setUsername(
          "lzqdiy");
                  user.setPassword(
          "lzqdiy");
                  session.save(user);
                  tx.commit();
                  HibernateUtil.closeCurrentSession();
              }


              
          public List<User> getUsers() throws HibernateException
              
          {
                  Session session 
          = HibernateUtil.getCurrentSession();
                  Transaction tx 
          = session.beginTransaction();
                  String sql 
          = "select u from User as u where u.username=:name";
                  Query query 
          = session.createQuery(sql);
                  query.setString(
          "name""lzqdiy");
                  List
          <User> list = query.list();
                  tx.commit();
                  HibernateUtil.closeCurrentSession();
                  
          return list;
              }


              
          public static void main(String[] args) throws HibernateException
              
          {
                  
          // TODO Auto-generated method stub
                  new HibernateTest().insertUser();
                  List
          <User> list = new HibernateTest().getUsers();
                  
          for (User user : list)
                  
          {

                      System.out.println(user.getUsername());
                      System.out.println(user.getPassword());
                  }

              }

          }

          以上的程序使用的數據庫是SQLServer2000,如果你想將數據庫更換為MySQL,只需將hibernate.cfg.xml更改如下:
          <?xml version='1.0' encoding='UTF-8'?>
          <!DOCTYPE hibernate-configuration PUBLIC
                    "-//Hibernate/Hibernate Configuration DTD 2.0//EN"
                    "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd"
          >

          <!-- Generated by MyEclipse Hibernate Tools.                   -->
          <hibernate-configuration>

          <session-factory>
              
          <property name="dialect">net.sf.hibernate.dialect.MySQLDialect</property>
              
          <property name="connection.url">jdbc:mysql://localhost:3306/login</property>
              
          <property name="connection.username">root</property>
              
          <property name="connection.password">root</property>
              
          <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
              
          <property name="myeclipse.connection.profile">myconn</property>
              
          <mapping resource="model/model.hbm.xml" />
          </session-factory>

          </hibernate-configuration>
          其他的源程序代碼都不需要更改,是不是很爽,呵呵。

          posted on 2007-06-09 20:51 我為J狂 閱讀(1150) 評論(3)  編輯  收藏 所屬分類: 開源框架

          評論

          # re: Hibernate使軟件適應不同的數據庫易如反掌 2007-06-09 21:27 itkui

          是很爽,不然hibernate干什么用呀?
          不用hibernate也可以,只需定義相關的接口就可以。
          將數據庫相關配置文件存放在xml文件中,利用properties類中的方法進行讀取。  回復  更多評論   

          # re: Hibernate使軟件適應不同的數據庫易如反掌 2007-06-09 21:47 我為J狂

          @itkui
          Hibernate的功能很強大,還有很多是我不太了解的,因此我還需要加倍努力。  回復  更多評論   

          # re: Hibernate使軟件適應不同的數據庫易如反掌 2007-06-10 02:46 sitinspring

          itkui 說得很對,不用H都可以隨便來.

          H是在領域對象和關系數據庫間搭橋梁用的,用了它,你應該更多考慮對象而不是DB.  回復  更多評論   

          <2007年6月>
          272829303112
          3456789
          10111213141516
          17181920212223
          24252627282930
          1234567

          導航

          統計

          常用鏈接

          留言簿(11)

          隨筆分類(48)

          文章分類(29)

          常去逛逛

          搜索

          積分與排名

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 星座| 石嘴山市| 红河县| 金乡县| 东港市| 岐山县| 永寿县| 奉节县| 周宁县| 沂水县| 开封县| 龙里县| 菏泽市| 新田县| 开平市| 大宁县| 明溪县| 镇宁| 西充县| 静海县| 楚雄市| 金坛市| 若羌县| 鄄城县| 灵山县| 汉源县| 彰化市| 湘潭县| 泾川县| 四子王旗| 阳信县| 庆元县| 板桥市| 潞城市| 荆门市| 昌宁县| 铁岭市| 资中县| 丹凤县| 昔阳县| 石狮市|