在Hibernate会话工厂中运行时切换数据源(基于标头)

时间:2018-03-28 06:37:41

标签: java spring hibernate

我有2个DB实例。每个人都为不同的客户。这是我的hibernate配置类:

public class HibernateConfiguration {

    @Autowired
    private Environment environment;

    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(new String[]{"com.mhycomoant.test.model"});
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
    }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
        dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
        return dataSource;
    }

    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        properties.put("hibernate.id.new_generator_mappings","false");
        return properties;
    }

    @Bean
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory s) {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(s);
        return transactionManager;
    }

   }

这是我的Dao课程

    @Repository
    @Transactional()
@EnableTransactionManagement
public class PersonDaoImpl implements PersonDao {

    @Autowired
    private SessionFactory sessionFactory;

    private Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }


    public void setSessionFactory(SessionFactory sf){
    this.sessionFactory = sf;
    }

    @Override
    public Serializable save(Person wt) {
        return getCurrentSession().save(wt);
    }

    @Override
    public List<Person> list() {
        throw new UnsupportedOperationException("Not supported yet.");
        //Session session = this.sessionFactory.openSession();
    //  List<WalletTransaction> personList = session.createQuery("from person").list();
    //  session.close();
    //  return personList;
    }

如何在运行时切换数据库?

0 个答案:

没有答案