当请求仅随数据库详细信息一起提供时,需要即时更改默认数据库设置

时间:2018-06-25 14:24:49

标签: hibernate spring-boot jpa spring-data-jpa spring-restcontroller

我一直被困在application.yml文件中具有默认数据库配置的设置中

因此,我的项目要求是,当请求附带数据库详细信息(用户名,URL,密码)时,需要更改数据库。

因此,每当请求包含数据库详细信息时。以下是请求应遵循的步骤。

第1步。Db连接应使用新的Db详细信息重置

步骤2。从传递的Db Details中获取连接,并从该DB中获取数据。

这是我的文件

默认application.yml

spring:
  profiles:
    active: "dev"
---
spring:
  profiles: dev
  datasource:
    url: jdbc:sqlserver://localhost:8181;databasename=MyExampleApplication
    driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
    username: demo
    password: demo@123
  jpa:
    properties:
      hibernate:
        dialect: org.hibernate.dialect.SQLServer2008Dialect
    hibernate:
      show_sql: true

这是我的应用程序启动后用于连接数据库的文件。

根据我的要求,我创建了以下文件。名称DatabaseExample

@Configuration
@EnableTransactionManagement
@ComponentScan("com.myexample.demo")
@PropertySource(value="classpath:application.yml")
@EnableJpaRepositories(
            basePackages = "com.myexample.demo",
            entityManagerFactoryRef = "myExamEntityManager",
            transactionManagerRef = "myExamTransactionManager")
    public class DatabaseExample {

    @Autowired
    DatabaseDao dbProperties;

        private Properties hibernateProperties() {
            Properties properties = new Properties();
            properties.put("hibernate.hbm2ddl.auto", true);
            properties.put("hibernate.dialect", "org.hibernate.dialect.SQLServer2008Dialect");
            properties.put("hibernate.temp.use_jdbc_metadata_defaults", "false");
            properties.put("hibernate.show_sql","true");
            properties.put("entitymanager.packages.to.scan","com.myexample.demo");
            properties.put("connection.release_mode","auto");
            return properties;
        }



        @Bean(name = "myExamDataSource")
            @Primary
            public DataSource athenaDataSource() {
                DriverManagerDataSource dataSource = new DriverManagerDataSource();

                // i am not sure about followings lines as I am autowiring the *dbproperties* so whenever the request comes with DbDetails the Instance already created at the time of setting the values. So this might not be created again 

                // also not sure does it have the values of it may have null? problem is How can I pas the values from frontend, also need to set it only when request comes with DB details, else the default file should be used for connection  

                //?? Also is it the right way to create datasource with Userpassed Db Details 

                dataSource.setDriverClassName(dbProperties.getDrivercclass());
                dataSource.setUrl(dbProperties.getUrl());
                dataSource.setUsername(dbProperties.getUsername());
                dataSource.setPassword(dbProperties.getPassword());
                return dataSource;
            }

        @Bean(name = "MyExamEntityManager")
        @Primary
        public LocalContainerEntityManagerFactoryBean athenaEntityManager() {
            LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
            em.setDataSource(athenaDataSource());
            em.setPackagesToScan(new String[] { "com.myexample.demo" });
            HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
            em.setJpaVendorAdapter(vendorAdapter);
            em.setJpaProperties(hibernateProperties());

            return em;
        }

        @Bean(name = "myExamTransactionManager")
        @Primary
        public PlatformTransactionManager athenaTransactionManager() {
            JpaTransactionManager transactionManager = new JpaTransactionManager();
            transactionManager.setEntityManagerFactory(athenaEntityManager().getObject());
            return transactionManager;
        }

        @Bean(name = "myExamSessionFactory")
        @Primary
        public LocalSessionFactoryBean athenaSessionFactory() {
            LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
            sessionFactoryBean.setDataSource(athenaDataSource());
            sessionFactoryBean.setPackagesToScan("com.myexample.demo");
            sessionFactoryBean.setHibernateProperties(hibernateProperties());
            return sessionFactoryBean;
        }



}

现在,仅当对控制器发出请求时,才需要初始化此类的Been

@RestController
class MyController{


        @Autowired
        private EntityManagerUtils emUtils;

        @RequestMapping(method = RequestMethod.GET,value = "/all/{dbName}")
        public Iterable<AthenaFeatures> getAll(@PathVariable("dbName") String dbName,Pageable pageable){

                                DatabaseDao dbProperties = new DatabaseDao();
                                dbProperties.setDrivercclass("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                                dbProperties.setUrl("jdbc:sqlserver://localhost:8181;databasename=MyExample2Application");
                                dbProperties.setUsername("demo1");
                                dbProperties.setPassword("demo@456");


                                setRepository(dbName);
                                return athenaFeaturesService.getAllAthenaFeaturess(pageable);
        }


        private void setRepository(String url){
            athenaFeatureRepository = emUtils.getJpaFactory().getRepository(AthenaFeaturesRepository.class);
        }

    }

这是我的实体类,用于动态创建数据库连接

@Component
public class EntityManagerUtils {

    @Autowired
    @Qualifier("athenaEntityManager")
    private EntityManager athenaDatabase;

    public EntityManager getEm(){
        return athenaDatabase;
    }

    public JpaRepositoryFactory getJpaFactory(){
        return new JpaRepositoryFactory( getEm() );
    }

}

注意:我是Spring-boot配置的新手,我只知道中级配置,请解释如何归档它。

有关问题的更多说明,请阅读我的DatabaseExample文件

0 个答案:

没有答案