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狂 阅读(1123) 评论(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)

常去逛逛

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜