Changing Persistence Unit dynamically - JPA

前端 未结 4 1278
被撕碎了的回忆
被撕碎了的回忆 2020-11-29 03:26

Persistence units in persistence.xml are created during building the application. As I want to change the database url at runtime, is there any way to modify the persistence

4条回答
  •  囚心锁ツ
    2020-11-29 04:07

    If you are using Thorntail framework, you can wire-up the persistence.xml file to fetch runtime variables from "project-defaults.yml" file.

    
        org.hibernate.ejb.HibernatePersistence
        com.package.jpa.EntityClass1
        com.package.jpa.EntityClass2
        com.package.jpa.EntityClass3
        
            
            
            
    
    
            
            
            
    
    
            
            
        
    
    
    

    Take note of the dynamic DB values in ${...} as the point to values in the project-default.yml file.

    Then you project-defaults.yml file will have an entry like this:

        thorntail:
           http:
             port: 8989
           datasources:
              data-sources:
                 my-postgres-ds:
                    driver-name: my-postgres-driver
                    connection-url: "jdbc:postgresql://localhost:5432/my-db-name"
                    user-name: my-user-name
                    password: "my-password#"
              jdbc-drivers:
                 my-postgres-driver:
                    driver-module-name: org.postgresql
                    driver-xa-datasource-class-name: org.postgresql.xa.PGXADataSource
    

    I expect this should also work for Spring boot using application.properties and persistence.xml

提交回复
热议问题