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

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

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

    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狂 閱讀(1147) 評論(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)

    常去逛逛

    搜索

    積分與排名

    最新評論

    閱讀排行榜

    評論排行榜

    主站蜘蛛池模板: 一级特黄录像免费播放中文版| 在线观看免费无码视频| 全部免费a级毛片| 国产午夜无码片免费| 亚洲最大成人网色香蕉| 国产亚洲精aa成人网站| 国产乱子精品免费视观看片| 免费的黄色的网站| 亚洲精品在线免费看| 亚洲午夜无码片在线观看影院猛 | 免费观看一区二区三区| 亚洲av成人综合网| 亚洲欧洲美洲无码精品VA| 久久水蜜桃亚洲av无码精品麻豆| www成人免费观看网站| 亚洲春色在线观看| 亚洲午夜无码AV毛片久久| 成年丰满熟妇午夜免费视频| a毛片免费全部播放完整成| 亚洲aⅴ无码专区在线观看| 久久久无码精品亚洲日韩按摩| 国产免费69成人精品视频| 特级aa**毛片免费观看| 久久亚洲AV成人无码国产 | 国产精品亚洲аv无码播放| 免费人成视频在线| 看全免费的一级毛片| 亚洲第一成年人网站| 337p日本欧洲亚洲大胆裸体艺术| 成人免费区一区二区三区 | 亚洲国产韩国一区二区| 国产国拍精品亚洲AV片| 国产免费人视频在线观看免费| 91嫩草国产在线观看免费| 99爱免费观看视频在线| 亚洲av极品无码专区在线观看| 亚洲国产高清人在线| 亚洲精品国产美女久久久| 亚洲伊人久久成综合人影院| 国产精品无码素人福利免费| 成人性生活免费视频|