`
feicer
  • 浏览: 133072 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Hibernate根据方言dialect动态连接多数据库

阅读更多

 

Hibernate根据方言dialect动态连接多数据库

由于最近需要在web项目中动态链接不同地址的数据库,且要链接的子数据库的信息在总数据库(即web项目的主数据库)的表中,所以动手写了一个类。

web项目试用了hibernate,动态生成的子数据库链接打算也用hibernate,虽然动态生成的sessionfactory类,以及Configuration配置没有子数据库的对象关系映射,但是使用 native SQL 也方便。

 

请看后来写的改进篇,有什么建议请留言------------

  Hibernate动态连接多数据库改进篇

-------------------------------------------------------


代码如下:

public class TempSessionFactory {

    /** 
     * Location of hibernate.cfg.xml file.
     * Location should be on the classpath as Hibernate uses  
     * #resourceAsStream style lookup for its configuration file. 
     * The default classpath location of the hibernate config file is 
     * in the default package. Use #setConfigFile() to update 
     * the location of the configuration file for the current session.   
     */
    //private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
	private final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private Configuration configuration = new Configuration(); 
    private org.hibernate.SessionFactory sessionFactory;
    //private static String configFile = CONFIG_FILE_LOCATION;

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

	public void setConfiguration(String dialect, String driverClass,
			String ipAddress, String port, String dataBaseName,
			String username, String password) {
		String connection_url = "";

		Configuration configuration = new Configuration();
		if (dialect.indexOf("MySQL") > -1) {
			System.out.println("%%%% DataBase type is MySql %%%%");
			connection_url = "jdbc:mysql://" + ipAddress + "/" + dataBaseName;
		} else if (dialect.indexOf("SQLServer") > -1) {
			System.out.println("%%%% DataBase type is SQLServer %%%%");
			connection_url = "jdbc:sqlserver://" + ipAddress + ":" + port
					+ ";DataBaseName=" + dataBaseName;
		} else if (dialect.indexOf("Oracle") > -1) {
			System.out.println("%%%% DataBase type is Oracle %%%%");
			connection_url = "jdbc:oracle:thin:@" + ipAddress + ":" + port
					+ ":" + dataBaseName;
			// configuration.setProperty("hibernate.connection.oracle.jdbc.V8Compatible","true");
		}

		configuration.setProperty("hibernate.dialect", dialect);
		configuration.setProperty("hibernate.connection.url", connection_url);
		configuration.setProperty("hibernate.connection.driver_class",
				driverClass);
		configuration.setProperty("hibernate.connection.username", username);
		configuration.setProperty("hibernate.connection.password", password);
		// configuration.setProperty("hibernate.default_schema", "dbo");
		// configuration.setProperty("hibernate.default_catalog", dataBaseName);
		// configuration.setProperty("hibernate.show_sql", "true");
		this.configuration = configuration;
	}
	/**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     *  
     */
    public Session getSession() 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 void rebuildSessionFactory() {
		try {
			//configuration.configure(configFile);
			sessionFactory = this.configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err
					.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}

	/**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

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

	/**
     *  return session factory
     *
     */
	public org.hibernate.SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
     *  return session factory
     *
     *	session factory will be rebuilded in the next call
     */
/*	public static void setConfigFile(String configFile) {
		HibernateSessionFactory.configFile = configFile;
		sessionFactory = null;
	}*/

	/**
     *  return hibernate configuration
     *
     */
	public Configuration getConfiguration() {
		return configuration;
	}
}



测试类代码:
在 databasename1 库中建 testtable表,字段id,name2个
在 databasename2 库中建 testtable2表,字段id,name2个

public class TestCase1 {

	public static void main(String[] args) {
		
		try{
			
			Configuration configuration1 = new Configuration();			
			TempSessionFactory tempSessionFactory1 = new TempSessionFactory(configuration1);
			tempSessionFactory1.setConfiguration("org.hibernate.dialect.SQLServerDialect","com.microsoft.sqlserver.jdbc.SQLServerDriver",
					"jdbc:sqlserver://*1.*1.*1.*1","1433","databasename1","sa","sa");
			Session session1=tempSessionFactory1.getSession();
			Transaction tx1 = session1.beginTransaction();
			Query query1 = session1.createSQLQuery("select  name as  aaa  from testtable ").setResultTransformer(
					Transformers.ALIAS_TO_ENTITY_MAP);
			Map obj1 = (Map)query1.setMaxResults(1).uniqueResult();
			System.out.println("fd1111===="+obj1.get("aaa"));
			
			Configuration configuration2 = new Configuration();			
			TempSessionFactory tempSessionFactory2 = new TempSessionFactory(configuration2);
			tempSessionFactory2.setConfiguration("org.hibernate.dialect.SQLServerDialect","com.microsoft.sqlserver.jdbc.SQLServerDriver",
					"jdbc:sqlserver://*2.*2.*2.*2","1433","databasename2","sa","sa");
			Session session2=tempSessionFactory2.getSession();
			Transaction tx2 = session2.beginTransaction();
			Query query2 = session2.createSQLQuery("select  name as  aaa  from testtable2 ").setResultTransformer(
					Transformers.ALIAS_TO_ENTITY_MAP);
			Map obj2 = (Map)query2.setMaxResults(1).uniqueResult();
			System.out.println("fd2222===="+obj2.get("aaa"));
			
	
		}catch (Exception e) {
			System.err.println(e);
			// TODO: handle exception
		}
	}
}

 

请看后来写的改进篇--------------------

 

  Hibernate动态连接多数据库改进篇

 

------------------------------------------

0
0
分享到:
评论
2 楼 feicer 2010-01-11  
注意:在 oracle中 使用 native sql 查询,别名自动会变成 大写的,
select  name as  aaa  from testtable2 
会变成
select  name as  AAA from testtable2 

System.out.println("fd2222===="+obj2.get("AAA"));
   才可以
1 楼 feicer 2010-01-07  
高手们,有没有更好的办法写 TempSessionFactory  类,有的话,留言说一下啊。。。

相关推荐

Global site tag (gtag.js) - Google Analytics