【问题标题】:How do I change database connection at runtime by changing only db url in hibernate's configuration in spring boot?如何通过在 Spring Boot 中仅更改休眠配置中的 db url 在运行时更改数据库连接?
【发布时间】:2019-01-15 04:03:05
【问题描述】:

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

【问题讨论】:

    标签: hibernate spring-boot jpa sessionfactory


    【解决方案1】:

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

    第一个: 创建多个数据源,根据您的需要配置和使用它是最好的指南:Using multiple data sources with Spring Boot

    第二个: 是的,您只能通过在运行时更改 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>
    

    然后,您可以在运行时根据需要设置属性值:

    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
    

    【讨论】:

    • 目前配置为第一方案。有没有办法重新配置第一个并更改configure中的url?
    • 如果要更改,则不能在运行时更改 URL,那么这违反了答案中提到的 spring。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 2020-07-27
    • 2022-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    相关资源
    最近更新 更多