简体   繁体   English

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

[英]Dynamically connecting to Database in Java(Spring Boot)

I Want to connect to database at every http request(In every request i will be getting database details from user).Can anyone suggest how to do it using spring-boot-starter-jpa.我想在每个 http 请求时连接到数据库(在每个请求中,我都会从用户那里获取数据库详细信息)。谁能建议如何使用 spring-boot-starter-jpa 来做到这一点。

I can't use properties file for database configuration details.我无法将属性文件用于数据库配置详细信息。 because details i will be getting from http request dynamically.因为我将从 http 请求动态获取详细信息。

I am using 2.0.0.M3 spring boot version.我使用的是 2.0.0.M3 spring boot 版本。

I would suggest you to better use native JDBC code to connect with database and perform query.我建议您更好地使用本机 JDBC 代码来连接数据库并执行查询。 if you want to use spring data jpa then you have to create bean for DataSource , EntityManagerFactory and JpaTransactionManager at runtime.如果要使用 spring 数据 jpa,则必须在运行时为DataSourceEntityManagerFactoryJpaTransactionManager创建 bean。

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.如果数据库详细信息将出现在每个用户请求中,并且您希望在每个 http 请求上连接数据库,那么这不是可取的,因为在没有数据库实例化的情况下,在应用程序启动时甚至没有实体管理器工厂。 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.您必须在每个请求上手动创建数据源、事务管理器、实体管理器等实例化和初始化,并将它们注册到 spring IOC 容器,在请求完成后,您必须从 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.但是没有人应该手动执行这个过程,因为它太老练和更复杂,我们正在负担这个实例化以自己销毁 bean。 Even spring manages it very well and we are making complexity by taking charge at our own.甚至 spring 也能很好地管理它,我们通过自己负责来制造复杂性。

我觉得直接连接用户的数据库可能不太合适。我建议做一个接口程序,把你需要的动态数据收集到一个数据库中。你不能在你的代码中改变连接参数的属性。

You need to load properties file of spring boot in a class using @ConfigurationProperties anotation.您需要使用@ConfigurationProperties注释在类中加载spring boot 的属性文件。

Also you need to call the database configuration api inside this class.您还需要在此类中调用数据库配置 api。

Same requirement and I am sure all the database I connect to would have the same structure相同的要求,我确信我连接的所有数据库都具有相同的结构

Any solution till now?到现在有什么解决办法吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM