hibernate动态读取配置及创建数据源

	public static Configuration initDBConfig(String dialect, String driver, String url, String user, String pwd){
		Configuration cfg = new Configuration().configure("/hibernate.cfg.xml");
		cfg.setProperty("hibernate.dialect", dialect);
		cfg.setProperty("hibernate.connection.driver_class", driver);
		cfg.setProperty("hibernate.connection.url", url);
		cfg.setProperty("hibernate.connection.username", user);
		cfg.setProperty("hibernate.connection.password", pwd);
		
		cfg.setProperty("hibernate.c3p0.max_size", DBConstant.getDBConf().getPoolMaxSize());
		cfg.setProperty("hibernate.c3p0.min_size", DBConstant.getDBConf().getPoolMinSize());
		cfg.setProperty("hibernate.c3p0.max_statements", DBConstant.getDBConf().getMaxStatements());
		return cfg;
	}

通过上面的函数,数据库的配置信息就无需使用hibernate.cfg.xml写死的配置,可以从其他的渠道进行读取,而无需改变的信息则可以默认使用hibernate.cfg.xml的配置。

	public static SessionFactory initSessionFactory(Configuration cfg) throws SmbDaoException{
		try{
			StandardServiceRegistryBuilder ssrbuilder = new StandardServiceRegistryBuilder()
					                                    .applySettings(cfg.getProperties());
			ServiceRegistry service = ssrbuilder.build();
			SessionFactory sessionFactory=cfg.buildSessionFactory(service);
			LOG.info("init hibernate success");
			return sessionFactory;
		}catch(Exception e){
			throw new SmbDaoException(e.getMessage(), e); 
		}
	}
第二个函数接收第一个函数的返回作为参数,这样就可以根据不同的配置,创建不同的数据源了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值