简体   繁体   English

如何通过在Spring Boot的hibernate配置中仅更改db url来更改运行时的数据库连接?

[英]How do I change database connection at runtime by changing only db url in hibernate's configuration in spring boot?

I am developing a Spring Boot application that uses Spring Data JPA and will need to connect to only url different but other all same database eg jdbc:sqlite:db1.db jdbc:sqlite:db2.db I need to create all datasources in runtime . 我正在开发一个使用Spring Data JPA的Spring Boot应用程序,它将仅需要连接到不同但其他所有相同数据库的url,例如jdbc:sqlite:db1.db jdbc:sqlite:db2.db我需要在运行时创建所有数据源。 I read a lot of things about it in stack and spring forums(eg AbstractRoutingDataSource) but all of these tutorials show how to create datasources from .properties configuration or static definition in java bean. 我在堆栈和春季论坛(例如AbstractRoutingDataSource)中阅读了很多有关它的内容,但是所有这些教程都展示了如何从.properties配置或Java bean中的静态定义创建数据源。 It is possible to create many datsources in runtime? 是否可以在运行时创建许多数据源? How to manage transactions and how to create many sessionFactories? 如何管理交易以及如何创建许多sessionFactories? It is possible to use @Transactional annotation? 可以使用@Transactional注释吗? What is the best method to do this? 最好的方法是什么? Can someone explain me how to do this 'step by step'? 有人可以解释一下我如何“逐步”执行此操作吗?

There are two solutions to this problem but I prefer the first one, the developer uses the second one but this is a violation of spring. 这个问题有两种解决方案,但我更喜欢第一种,开发人员使用第二种,但这违反了spring。

First one: Create Multiple data sources, configure it and use it according to your need here is the best guide to follow: Using multiple data sources with Spring Boot 第一个:创建多个数据源,根据需要进行配置和使用,这里是遵循的最佳指南: 在Spring Boot中使用多个数据源

Second one: Yep you can change database connection at runtime only by changing hibernate.cfg.xml property value at runtime firstly here is a code to write hibernate.cfg.xml file: 第二个:是的,您只能在运行时更改hibernate.cfg.xml属性值,才能在运行时更改数据库连接。首先,这是编写hibernate.cfg.xml文件的代码:

<session-factory>
    <!-- Database connection settings -->
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url"></property>
    <property name="connection.username"></property>
    <property name="connection.password"></property>
    //other things goes here
</session-factory>

Then you can set property values at runtime like where you want: 然后,您可以在运行时在所需位置设置属性值:

Configuration configuration = new Configuration();
configuration.configure();
// <!-- Database connection settings -->
configuration.setProperty("hibernate.connection.url", URL);//Here pass connection url
configuration.setProperty("hibernate.connection.username", USERNAME);//Here your connection username
configuration.setProperty("hibernate.connection.password", PASSWORD);//Here your connection password
SessionFactory sessionFactory = configuration.buildSessionFactory();
//Here your transaction begin

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

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