Read Environment Variables in persistence.xml file

前端 未结 3 1272
陌清茗
陌清茗 2020-12-16 02:53

I want to read environment variables inside persistence.xml file.

Idea is that i don\'t want my database details to be read from properties file as

3条回答
  •  难免孤独
    2020-12-16 03:08

    You can update properties in a persistence unit by supplying a Map (see this).

    Conveniently, environment variables can be retrieved as a Map (see this).

    Put the two together and you can dynamically update properties in your persistence unit with environment variables.

    EDIT: simple example...

    persistence.xml...

    
        
            oracle.toplink.essentials.PersistenceProvider
        
        false
        
            
            
            
            
            
        
    
    

    code that updates persistence.xml "default" unit with environment variables...

    Map env = System.getenv();
    Map configOverrides = new HashMap();
    for (String envName : env.keySet()) {
        if (envName.contains("DB_USER")) {
            configOverrides.put("toplink.jdbc.user", env.get(envName)));    
        }
        // You can put more code in here to populate configOverrides...
    }
    
    EntityManagerFactory emf =
        Persistence.createEntityManagerFactory("default", configOverrides);
    

提交回复
热议问题