RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 1013721
Accepted
Antonio112009
Antonio112009
Asked:2020-08-15 10:26:33 +0000 UTC2020-08-15 10:26:33 +0000 UTC 2020-08-15 10:26:33 +0000 UTC

将 Hibernate 的登录名、密码和 URL 存储在单独的文件中

  • 772

使用 Hibernate(不是在春天!!!!!!),我和你们中的许多人一样,懒得手动设置数据库。在项目中使用自动文件搜索和自动配置很好。一切都会好的,但是在 Github 上需要一个新项目,但我不想显示登录名、密码和 URL。

需要一个示例代码,其中 Hibernate 将获取主文件和机密文件并在程序启动时自动配置。

目前我正在使用hibernate.cfg.xml,但application.properties也接受了答案。

我的(工作)代码示例:

HibernateUtil.java:

import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateUtil {
    private static StandardServiceRegistry registry;
    private static SessionFactory sessionFactory;

    public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            try {
                // Create registry
                registry = new StandardServiceRegistryBuilder().configure().build();

                // Create MetadataSources
                MetadataSources sources = new MetadataSources(registry);

                // Create Metadata
                Metadata metadata = sources.getMetadataBuilder().build();

                // Create SessionFactory
                sessionFactory = metadata.getSessionFactoryBuilder().build();

            } catch (Exception e) {
                e.printStackTrace();
                if (registry != null) {
                    StandardServiceRegistryBuilder.destroy(registry);
                }
            }
        }
        return sessionFactory;
    }

    public static void shutdown() {
        if (registry != null) {
            StandardServiceRegistryBuilder.destroy(registry);
        }
    }
}

休眠.cfg.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- JDBC Database connection settings -->
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>

        <!--SERVER-->
        <!--<property name="connection.url">jdbc:mysql://localhost:3306/db?useSSL=false&amp;autoReconnect=true&amp;createDatabaseIfNotExist=true&amp;</property>-->
        <property name="connection.username">USERNAME</property>
        <property name="connection.password">PASSWORD</property>

        <property name="connection.provider_class">org.hibernate.hikaricp.internal.HikariCPConnectionProvider</property>
        <property name="hibernate.hikari.connectionTimeout">20000</property>
        <property name="hibernate.hikari.minimumIdle">10</property>
        <property name="hibernate.hikari.maximumPoolSize">20</property>
        <property name="hibernate.hikari.idleTimeout">300000</property>


        <!-- JDBC connection pool settings ... using built-in test pool -->
        <property name="connection.pool_size">1</property>

        <!-- Select our SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>

        <!-- Echo the SQL to stdout -->
        <property name="show_sql">false</property>
        <!--<property name="show_sql">true</property>-->

        <!-- Set the current session context -->
        <property name="current_session_context_class">thread</property>

        <!-- Drop and re-create the database schema on startup -->
        <!--<property name="hbm2ddl.auto">create</property>-->
        <!--<property name="hbm2ddl.auto">create-drop</property>-->
        <!--<property name="hbm2ddl.auto">update</property>-->
        <property name="hbm2ddl.auto">validate</property>
        <!-- dbcp connection pool configuration -->
        <property name="hibernate.dbcp.initialSize">5</property>
        <property name="hibernate.dbcp.maxTotal">20</property>
        <property name="hibernate.dbcp.maxIdle">10</property>
        <property name="hibernate.dbcp.minIdle">5</property>
        <property name="hibernate.dbcp.maxWaitMillis">-1</property>

        <!--<mapping class="entities.User" />-->
        <!--<mapping class="entities.Servers" />-->
        <!--<mapping class="entities.Authorities" />-->
        <!--<mapping class="entities.Language" />-->
        <!--<mapping class="entities.ServerMessage" />-->
        <!--<mapping class="entities.MessageServer" />-->


    </session-factory>
</hibernate-configuration>
java
  • 3 3 个回答
  • 10 Views

3 个回答

  • Voted
  1. Tankred
    2020-09-13T15:56:37Z2020-09-13T15:56:37Z

    如果您不使用 Spring 工具包或将设置移动到单独的属性文件中的任何其他可能性,那么您可以执行以下操作:

    制作 hibernate.cfg.xml 的副本,随意命名,例如 hibernate.mock.cfg.xml。在此文件中,将密码和名称更改为 stubs。将原始 hibernate.cfg.xml 文件添加到 gitignore。

    然后 SessionFactory 声明块将如下所示:

    public static SessionFactory getSessionFactory() {
           if (sessionFactory == null) {
              try {
                   sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
              } 
                   catch (ConfigurationException noConfEx)
              {
                   sessionFactory = new Configuration().configure("hibernate.mock.cfg.xml").buildSessionFactory();
              }
              catch (Throwable ex) {
                   throw new ExceptionInInitializerError(ex);
              }
       return sessionFactory;
    }
    

    上面的代码是这样工作的:当您尝试获取不在 git 中的 hibernate.cfg.xml 时,将从存根中读取配置。因此,为了解决这个问题,我们使用了 hibernate 中的标准配置选项。您可以在此处阅读有关此内容的更多信息:https ://docs.jboss.org/hibernate/orm/3.5/reference/en/html/session-configuration.html

    或者,根据类似的原则:

    public static SessionFactory getSessionFactory() {
               if (sessionFactory == null) {
                  try {
                       sessionFactory = new Configuration().configure("hibernate.cfg.xml")
                  .setProperty("hibernate.connection.username", LoginHandler.getUserName())
                  .setProperty("hibernate.connection.password", LoginHandler.getPassword())
                  .buildSessionFactory();
                  } 
                  catch (Throwable ex) {
                       throw new ExceptionInInitializerError(ex);
                  }
           return sessionFactory;
        }
    

    在这种情况下,您将需要编写一个 LoginHandler 类,该类将从正确的位置(例如,从不同的属性)获取必要的登录名和密码。

    • 1
  2. maklas
    2020-09-10T16:32:15Z2020-09-10T16:32:15Z

    将属性文件添加到项目中。例如,dbParams.properties在哪里写下地址、端口、登录名和密码。启动时,从此文件中获取数据并通过StandardServiceRegistryBuilder. 并且properties文件本身就是.gitignore中的菜园所以没有上传到github。以任何安全的方式将其传递给合适的人。

    • 0
  3. Best Answer
    Antonio112009
    2020-09-15T23:01:29Z2020-09-15T23:01:29Z

    这个答案将被修改。

    特别感谢zdadco帮助我找到这个问题的答案。

    春天+休眠(+ Maven)

    如果您使用的是 Spring + Hibernate,请执行以下操作:

    1. 在文件夹Resources(文件所在的位置application.properties)中创建一个文件database.properties
    2. 例如,在这个文件中,我们放置了以下数据:
    spring.datasource.driver-class-name=DRIVER
    spring.datasource.url=URL
    spring.datasource.username=USERNAME
    spring.datasource.password=PASSWORD
    
    1. 在主类(started 类)中,我们添加以下几行@PropertySource("classpath:database.properties"),最终结果如下:
    @SpringBootApplication
    @PropertySource("classpath:database.properties")
    public class Launch{
    
        public static void main(String[] args) {
            SpringApplication.run(Launch.class, args);
        }
    
    }
    
    • 0

相关问题

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    根据浏览器窗口的大小调整背景图案的大小

    • 2 个回答
  • Marko Smith

    理解for循环的执行逻辑

    • 1 个回答
  • Marko Smith

    复制动态数组时出错(C++)

    • 1 个回答
  • Marko Smith

    Or and If,elif,else 构造[重复]

    • 1 个回答
  • Marko Smith

    如何构建支持 x64 的 APK

    • 1 个回答
  • Marko Smith

    如何使按钮的输入宽度?

    • 2 个回答
  • Marko Smith

    如何显示对象变量的名称?

    • 3 个回答
  • Marko Smith

    如何循环一个函数?

    • 1 个回答
  • Marko Smith

    LOWORD 宏有什么作用?

    • 2 个回答
  • Marko Smith

    从字符串的开头删除直到并包括一个字符

    • 2 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5