我想在休眠状态下连接到两台服务器。但我使用 java 类作为配置。如何让会话工厂知道它将使用连接一或连接二。
这是我的课:
@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;
}
}
我想添加另一个连接:
String url = "jdbc:oracle:thin:@//yyyy:yyyy/yyyy";
String username = "yyyy";
String password = "yyyy";
如何使用一个连接或另一个连接向 SessionFactory 提供信息?
这是使用会话工厂的示例:
@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);
}
}