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

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

 

本人曾经写过一篇

Hibernate根据方言dialect动态连接多数据库  的文章,发现效率不高,每次访问其他数据库,都要动态生成一个 sessionFactory实例,不算是个好的解决方法,后来查看hibernate源码,发现org.hibernate.cfg.Configuration类中有一个保护方法:

	protected void reset() {
……
	}

 

重写Configuration类,在动态的跳转不同数据库的时候,不用重新生成sessionFactory实例,发现效果不错。

故以此记录我的方法:

 

1. 自己重写的Configuration类,extends org.hibernate.cfg.Configuration

 

public class HibernateConfiguration extends org.hibernate.cfg.Configuration {

	public HibernateConfiguration() {
		super();
	}

	public void reset() {
		super.reset();
	}

	public HibernateConfiguration(String dialect, String driverClass,
			String ipAddress, String port, String dataBaseName,
			String username, String password) throws HibernateException {
		String connection_url = "";
		if (dialect.indexOf("MySQL") > -1) {
			connection_url = "jdbc:mysql://" + ipAddress + "/" + dataBaseName;
		} else if (dialect.indexOf("SQLServer") > -1) {
			connection_url = "jdbc:sqlserver://" + ipAddress + ":" + port
					+ ";DataBaseName=" + dataBaseName;
		} else if (dialect.indexOf("Oracle") > -1) {
			connection_url = "jdbc:oracle:thin:@" + ipAddress + ":" + port
					+ ":" + dataBaseName;
		} else {
			throw new HibernateException("The dialect was not allowed.==fd=="
					+ dialect);
		}

		super.setProperty("hibernate.dialect", dialect);
		super.setProperty("hibernate.connection.url", connection_url);
		super.setProperty("hibernate.connection.driver_class", driverClass);
		super.setProperty("hibernate.connection.username", username);
		super.setProperty("hibernate.connection.password", password);
		// super.setProperty("hibernate.show_sql", "true");
	}

	public HibernateConfiguration(String dialect, String driverClass,
			String ipAddress, String port, String dataBaseName,
			String username, String password, String schema, String catalog)
			throws HibernateException {
		String connection_url = "";
		if (dialect.indexOf("MySQL") > -1) {
			connection_url = "jdbc:mysql://" + ipAddress + "/" + dataBaseName;
		} else if (dialect.indexOf("SQLServer") > -1) {
			connection_url = "jdbc:sqlserver://" + ipAddress + ":" + port
					+ ";DataBaseName=" + dataBaseName;
		} else if (dialect.indexOf("Oracle") > -1) {
			connection_url = "jdbc:oracle:thin:@" + ipAddress + ":" + port
					+ ":" + dataBaseName;
		} else {
			throw new HibernateException("The dialect was not allowed.==fd=="
					+ dialect);
		}

		super.setProperty("hibernate.dialect", dialect);
		super.setProperty("hibernate.connection.url", connection_url);
		super.setProperty("hibernate.connection.driver_class", driverClass);
		super.setProperty("hibernate.connection.username", username);
		super.setProperty("hibernate.connection.password", password);
		super.setProperty("hibernate.default_schema", schema);
		super.setProperty("hibernate.default_catalog", catalog);
		// super.setProperty("hibernate.show_sql", "true");
	}

}

 

2. TempSessionFactory 的工厂类,这里把各个对象都变成了 static ,类也是static 类了,每次调用,都不用生成一个sessionFactory实例了,主要还是自己定义了一个reflashSessionFactory方法,对每次不同的数据库连接进行动态加载,其他的就是hibernate.cfg.xml 加载的问题,首次默认加载是用hibernate2.cfg.xml,其他时候就才用最新设置的参数,用了自定义类HibernateConfiguration 。 见下:

 

import org.hibernate.HibernateException;
import org.hibernate.Session;
import com.tools.hibernate.utils.HibernateConfiguration;

public class TempSessionFactory {

	.......//略


	public static void reflashSessionFactory(
			HibernateConfiguration tempConfiguration) {
		try {
			// configuration.configure(configFile);
			if (tempConfiguration.getProperty("hibernate.dialect").equals(
					configuration.getProperty("hibernate.dialect"))
					&& tempConfiguration
							.getProperty("hibernate.connection.url")
							.equalsIgnoreCase(
									configuration
											.getProperty("hibernate.connection.url"))
					&& tempConfiguration
							.getProperty("hibernate.connection.username")
							.equals(
									configuration
											.getProperty("hibernate.connection.username"))
					&& tempConfiguration
							.getProperty("hibernate.connection.password")
							.equals(
									configuration
											.getProperty("hibernate.connection.password"))) {

				System.out.println("%%%% TempSessionFactory is created aready!!-fd %%%%");
				// sessionFactory = configuration.buildSessionFactory();
			} else {
				closeSession();
				closeSessionFactory();
				configuration.reset();
				configuration = tempConfiguration;
				sessionFactory = configuration.buildSessionFactory();
				System.out.println("%%%% TempSessionFactory is reflashed here!!-fd %%%%");
			}
		} catch (Exception e) {
			System.err.println("%%%% Error Reflashing TempSessionFactory %%%%");
			e.printStackTrace();
		}
	}

	......//略
}

 

3. 顺便发一下测试类,自己在不同服务器上面 建几个数据库,建几张测试表,就可以了:

 

	public static void main(String[] args) {
		try{
			
			String timeFormat = "yyyy-MM-dd HH:mm:ss";
			SimpleDateFormat sdf = new SimpleDateFormat(timeFormat); 

			
			HibernateConfiguration configuration1 = new HibernateConfiguration("org.hibernate.dialect.SQLServerDialect","com.microsoft.sqlserver.jdbc.SQLServerDriver",
					"255.255.255.255","1433","dbname1","sa","sa");
			System.out.println("hibernate.connection.url==1="+TempSessionFactory.getConfiguration().getProperty("hibernate.connection.url"));
			TempSessionFactory.reflashSessionFactory(configuration1);			
			System.out.println("hibernate.connection.url==2="+TempSessionFactory.getConfiguration().getProperty("hibernate.connection.url"));
			
			Session session1=TempSessionFactory.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"));

			
			
			
			System.out.println("hibernate.connection.url==3="+TempSessionFactory.getConfiguration().getProperty("hibernate.connection.url"));
			HibernateConfiguration configuration2 = new HibernateConfiguration("org.hibernate.dialect.Oracle10gDialect","oracle.jdbc.driver.OracleDriver",
					"255.255.255.255","1521","orclDB1","username","passwd");			
			TempSessionFactory.reflashSessionFactory(configuration2);
			
			System.out.println("hibernate.connection.url==4="+TempSessionFactory.getConfiguration().getProperty("hibernate.connection.url"));
			session1=TempSessionFactory.getSession();
			tx1 = session1.beginTransaction();
			Query query2 = session1.createSQLQuery("select testname1 AAA from testtable1 ").setResultTransformer(
					Transformers.ALIAS_TO_ENTITY_MAP);
			Map obj2 = (Map)query2.setMaxResults(1).uniqueResult();
			System.out.println("fd2222===="+obj2.get("AAA"));
			
			
			
			
			System.out.println("hibernate.connection.url==5="+TempSessionFactory.getConfiguration().getProperty("hibernate.connection.url"));
			HibernateConfiguration configuration3 = new HibernateConfiguration("org.hibernate.dialect.Oracle10gDialect","oracle.jdbc.driver.OracleDriver",
					"255.255.255.255","1521","orclDB2","username","passwd");
			TempSessionFactory.reflashSessionFactory(configuration3);
			System.out.println("hibernate.connection.url==6="+TempSessionFactory.getConfiguration().getProperty("hibernate.connection.url"));
			session1=TempSessionFactory.getSession();
			tx1 = session1.beginTransaction();
			Query query3 = session1.createSQLQuery("select testname1 AAA from testtable2 ").setResultTransformer(
					Transformers.ALIAS_TO_ENTITY_MAP);
			Map obj3 = (Map)query3.setMaxResults(1).uniqueResult();
			System.out.println("fd3333===="+obj3.get("AAA"));
			
			
		}catch (Exception e) {
			System.err.println(e);
		}
	}

 

有什么好的建议,请留言。。。。。。。。。。。。。。。。。。。

转载注明 出处。。。。。。。。。。。。。。。。。。。。。。。。。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SpringBoot是现在主流的Java Web开发框架之一,其具有简洁、高效的特点,可以极大地简化开发者的开发流程,提高项目开发的效率。对于许多需要从数据库中读取数据初始数据的项目而言,如何尽最大可能地减少开发者的工作量以及提高用户体验就变得尤为关键。 SpringBoot提供了一种简单的方法来在启动应用程序时加载数据到数据库中,它借助了JdbcTemplate的实现。首先,开发者需要编辑一个用于实现阶段性数据加载的数据文件,例如“data.sql”或“schema.sql”,并将其放置在resources目录下。接下来,开发者需要在application.properties文件中添加SpringBoot与数据库连接配置。 在项目启动时,SpringBoot会自动扫描Classpath下的sql文件,并在应用程序启动时自动执行这些SQL命令。这意味着,当应用程序启动时,数据库中将包含在sql文件中命令定义的表和数据。在某些情况下,这些命令可能包含必需的存储过程、触发器和其他数据库对象。 使用SpringBoot加载数据库数据还有其他的方法,例如可以使用Spring Data JPA、Hibernate和Mybatis等持久化框架,将我们想要的数据插入到数据库中。这些方式的实现细节和原理都不同,但是它们实现的目标是相同的——减少开发者的工作量并提高项目开发效率。 综上所述,SpringBoot提供了一种简单的方法来在启动应用程序时加载数据到数据库中。通过这种方法,开发者可以更加迅速地将项目开发、测试和部署到生产环境,并且可以改进用户体验,从而为应用程序提供更好的价值和功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值