I want to connect to two servers on hibernate. But i am using java class as configuration. How give Session factory know it will use connection one or connection two.
this is my class:
@Configuration
@ComponentScan(basePackages = {"id.bni.hcms"})
@EnableTransactionManagement
public class RepositoryConfig {
@Bean(name = "dataSource")
public DataSource initDataSource(){
System.out.println("datasource inited initDataSource" );
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException ex) {
}
String url = "jdbc:oracle:thin:@//xxx.xxx.xx.xxx:xxx/xxxx";
String username = "xxx";
String password = "xxxx";
ConnectionFactory cf = new DriverManagerConnectionFactory(url, username, password);
PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, null);
GenericObjectPool<PoolableConnection> cp = new GenericObjectPool<>(pcf);
pcf.setPool(cp);
return new PoolingDataSource<>(cp);
}
@Bean(name = "sessionFactory")
public LocalSessionFactoryBean sessionFactoryBean(DataSource dataSource){
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean();
sfb.setDataSource(dataSource);
sfb.setPackagesToScan("id.bni.hcms");
Properties props = sfb.getHibernateProperties();
props.put("hibernate.format_sql", true);
props.put("hibernate.show_sql", true);
props.put("hibernate.dialect", "org.hibernate.dialect.Oracle9iDialect");
return sfb;
}
@Bean(name = "transactionManager")
public PlatformTransactionManager getHibernateTransactionManager(SessionFactory sessionFactory){
HibernateTransactionManager trxMgr = new HibernateTransactionManager(sessionFactory);
return trxMgr;
}
}
i want to add another connection :
String url = "jdbc:oracle:thin:@//yyyy:yyyy/yyyy";
String username = "yyyy";
String password = "yyyy";
how to give information to SessionFactory using one connection or another connection?
this is example using session factory:
@Repository
public class KaryawanDaoImpl implements KaryawanDao{
@Autowired
private SessionFactory sessionFactory;
@Override
@Transactional(propagation = Propagation.REQUIRED)
public Karyawan find(String username, String password) {
String hql = " SELECT * from table";
Query query = sessionFactory.getCurrentSession().createSQLQuery(hql).addEntity(Karyawan.class);
query.setString("user", username);
query.setString("pwd", password);
Karyawan result = (Karyawan)query.uniqueResult();
return result;
}
@Override
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
public void save(Karyawan e) {
sessionFactory.getCurrentSession()
.saveOrUpdate(e);
}
}
Using annotation mappings as an example:
Then use sf1 and sf2 to get the sessions for each database. For mapping files, you just use cfg.addClass instead of addAnnotatedClass. Put the cfg.xml files in the root package in this case. Those will have the Oracle or MySQL dialect and connection information.