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);
}
}
第二个函数接收第一个函数的返回作为参数,这样就可以根据不同的配置,创建不同的数据源了。