<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    Hibernate使軟件適應(yīng)不同的數(shù)據(jù)庫易如反掌

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

    源代碼
    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());
            }

        }

    }

    以上的程序使用的數(shù)據(jù)庫是SQLServer2000,如果你想將數(shù)據(jù)庫更換為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狂 閱讀(1147) 評(píng)論(3)  編輯  收藏 所屬分類: 開源框架

    評(píng)論

    # re: Hibernate使軟件適應(yīng)不同的數(shù)據(jù)庫易如反掌 2007-06-09 21:27 itkui

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

    # re: Hibernate使軟件適應(yīng)不同的數(shù)據(jù)庫易如反掌 2007-06-09 21:47 我為J狂

    @itkui
    Hibernate的功能很強(qiáng)大,還有很多是我不太了解的,因此我還需要加倍努力。  回復(fù)  更多評(píng)論   

    # re: Hibernate使軟件適應(yīng)不同的數(shù)據(jù)庫易如反掌 2007-06-10 02:46 sitinspring

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

    H是在領(lǐng)域?qū)ο蠛完P(guān)系數(shù)據(jù)庫間搭橋梁用的,用了它,你應(yīng)該更多考慮對象而不是DB.  回復(fù)  更多評(píng)論   

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

    導(dǎo)航

    統(tǒng)計(jì)

    常用鏈接

    留言簿(11)

    隨筆分類(48)

    文章分類(29)

    常去逛逛

    搜索

    積分與排名

    最新評(píng)論

    閱讀排行榜

    評(píng)論排行榜

    主站蜘蛛池模板: 亚洲av成人无码久久精品| 亚洲第一男人天堂| 可以免费看黄的网站| 亚洲人成无码网站在线观看| gogo全球高清大胆亚洲| 好男人看视频免费2019中文| 亚洲成a人片在线观看无码| 曰批视频免费40分钟试看天天| 国产精品亚洲专区无码牛牛| 国产亚洲一区二区三区在线观看 | 国产91免费在线观看| 羞羞漫画页面免费入口欢迎你| 亚洲αv在线精品糸列| 女人18毛片a级毛片免费视频| 中国在线观看免费的www| 亚洲一区二区三区高清不卡 | 亚洲小视频在线观看| 免费jjzz在线播放国产 | 日产乱码一卡二卡三免费| 日韩免费观看一区| 国产亚洲精品91| 亚洲另类精品xxxx人妖| 久久久久亚洲AV成人网人人软件 | 亚洲国产人成网站在线电影动漫| 热久久精品免费视频| 精品国产亚洲一区二区三区在线观看| 亚洲国产精品成人久久| 免费一级毛片不卡不收费| 四虎在线免费视频| 任你躁在线精品免费| 猫咪免费人成在线网站| 久久夜色精品国产噜噜亚洲a| 亚洲AV无码一区二区三区DV| 免费一级毛片女人图片| 日韩欧美一区二区三区免费观看 | 国产人成亚洲第一网站在线播放| 国产成A人亚洲精V品无码性色| 免费成人在线观看| 青青草国产免费久久久91| 2022久久国产精品免费热麻豆| a毛片全部免费播放|