【问题标题】:How to make credentials in persistence.xml programmatic?如何使persistence.xml中的凭据编程?
【发布时间】:2021-12-14 06:40:00
【问题描述】:

我有用于加载数据库和连接的 persistence.xml 文件。

我的用户名和密码是这样存储的:

            <!-- MySQL -->
            <property name="javax.persistence.jdbc.url"
                      value="jdbc:mysql://localhost:3306/mydatabase"/>

            <!-- Credentials -->
            <property name="javax.persistence.jdbc.user"
                      value="this is user"/>
            <property name="javax.persistence.jdbc.password"
                      value="this is password"/>

现在我有一个要求,不要像这样将这些存储在代码库中,而是希望通过线路以编程方式获取它们。我怎样才能做到这一点?

【问题讨论】:

    标签: java jpa spring-data-jpa persistence persistence.xml


    【解决方案1】:

    要动态设置值,您可以这样做:

    在 config.properties 中设置这些东西然后访问它们

    jdbc.url=jdbc:mysql://localhost:3306/my_database
    jdbc.username=root
    jdbc.password=123
    
    <property name="javax.persistence.jdbc.url" value="${jdbc.url}" />
    <property name="javax.persistence.jdbc.password" value="${jdbc.properties}" />
    

    或者如果你想在控制器中获取它们,可以使用“EntityManagerFactory”来获取它们

    EntityManagerFactory emf = entityManager.getEntityManagerFactory();
    Map<String, Object> emfProperties = emf.getProperties();
    
    String url = (String) emfProperties.get("javax.persistence.jdbc.url");
    String user = (String) emfProperties.get("javax.persistence.jdbc.user");
    String password = (String) emfProperties.get("javax.persistence.jdbc.password");
    

    【讨论】:

    • 你能详细说明一下吗?我只有 jpa 而不是休眠
    • 您可以使用jpa存储库,请您详细说明您的问题and want to fetch them programatically through a wire.
    猜你喜欢
    • 2011-05-31
    • 2019-08-25
    • 2017-05-24
    • 1970-01-01
    • 1970-01-01
    • 2014-04-12
    • 2019-05-06
    • 2011-02-10
    • 1970-01-01
    相关资源
    最近更新 更多