在Java中动态连接到数据库(Spring Boot)

时间:2017-08-04 09:53:04

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

我希望在每个http请求时连接到数据库(在每个请求中我都会从用户那里获取数据库详细信息)。任何人都可以建议如何使用spring-boot-starter-jpa来完成。

我无法使用属性文件来获取数据库配置详细信息。 因为我将动态地从http请求中获取详细信息。

我使用的是2.0.0.M3春季启动版。

5 个答案:

答案 0 :(得分:2)

我建议您更好地使用本机JDBC代码连接数据库并执行查询。如果你想使用spring数据jpa,那么你必须在运行时为DataSourceEntityManagerFactoryJpaTransactionManager创建bean。

答案 1 :(得分:1)

If database details will come in every user request and you want connect database on every http request, then it is not preferable because you will not have even entity manager factory on application startup without database instantiation. However in this situation you would have to manually manage all those stuff. You have to create datasource, transaction manager , entity manager etc. instantiation and initialization on each request manually and register those with spring IOC container and after the request completion you have to manually remove (unregister) those instances from Spring IOC. You can alos create interceptors for that. But no one should do this manually process because it is so hactic and more complex and we are making burden of this instantiation to destroy of beans on our own. Even spring manages it very well and we are making complexity by taking charge at our own.

答案 2 :(得分:0)

我认为立即连接用户数据库可能不合适。我建议制作一个接口程序,以便在一个数据库中收集所需的动态数据。您无法在代码中更改连接参数的属性。

答案 3 :(得分:0)

您需要使用@ConfigurationProperties anotation在类中加载spring boot的属性文件。

此外,您还需要在此类中调用数据库配置API。

答案 4 :(得分:0)

相同的要求,我确信我连接的所有数据库都具有相同的结构

到目前为止有什么解决方案吗?

相关问题