如何在运行时通过在 Spring 引导中仅更改休眠配置中的数据库 url 来更改数据库连接?



我正在开发一个使用 Spring Data JPA 的 Spring Boot 应用程序,并且只需要连接到不同但其他所有相同数据库的 url,例如 jdbc:sqlite:db1.db jdbc:sqlite:db2.db我需要在运行时创建所有数据源。我在堆栈和 spring 论坛(例如 AbstractRoutingDataSource(中读到了很多关于它的内容,但所有这些教程都展示了如何在 java bean 中从 .properties 配置或静态定义创建数据源。是否可以在运行时创建许多数据源?如何管理事务以及如何创建多个会话工厂?可以使用@Transactional注释吗?最好的方法是什么?有人可以解释我如何"一步一步"地做到这一点吗?

这个问题有两种解决方案,但我更喜欢第一种,开发人员使用第二种,但这违反了 spring。

第一个:创建多个数据源,根据需要配置和使用 这是要遵循的最佳指南:在 Spring 引导中使用多个数据源

第二个:是的,您只能通过更改休眠来更改运行时的数据库连接.cfg.xml运行时的属性值首先,这是编写休眠.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>

然后,您可以在运行时设置属性值,如您想要的位置:

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

最新更新