Read Environment Variables in persistence.xml file

前端 未结 3 1261
陌清茗
陌清茗 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...

    <persistence-unit name="default" transaction-type="RESOURCE_LOCAL">
        <provider>
            oracle.toplink.essentials.PersistenceProvider
        </provider>
        <exclude-unlisted-classes>false</exclude-unlisted-classes>
        <properties>
            <property name="toplink.logging.level" value="INFO"/>
            <property name="toplink.jdbc.driver" value="oracle.jdbc.OracleDriver"/>
            <property name="toplink.jdbc.url" value="jdbc:oracle:thin:@myhost:l521:MYSID"/>
            <property name="toplink.jdbc.password" value="tiger"/>
            <property name="toplink.jdbc.user" value="scott"/>
        </properties>
    </persistence-unit>
    

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

    Map<String, String> env = System.getenv();
    Map<String, Object> configOverrides = new HashMap<String, Object>();
    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);
    
    0 讨论(0)
  • 2020-12-16 03:11

    I don't think this will cover EMs created via injection. Worse, I think EMs created through EMF can only be EXTENDED (eg equivalent to the annotation @PersistenceContext(type = PersistenceContextType.TRANSACTION) opposed to EXTENDED) so that if one requires a transaction EM, one must use injection.

    I'm wondering if its possible to physically rewrite the persistence.xml file at runtime. Problem one being, ability to rewrite the file (permissions, being able to get to it in META-INF etc), and second, rewriting it before its opened for the first time by JPA (which I thinking happens the first time an injected EM field is actually referenced by application code)

    0 讨论(0)
  • 2020-12-16 03:31

    You could use this working example.

    It gets all properties defined in the persistence.xml from the PersistenceUnitInfo instance which is obtained from the EntityManagerFactory (by using eclipseLink specific implementations). These properties get replaced with the values defined in environment variables.

    0 讨论(0)
提交回复
热议问题