How to include properties from external file to hibernate.cfg.xml?

后端 未结 3 1548
渐次进展
渐次进展 2020-12-07 02:52

I need to be able to store database config properties in src|main|java|dbConnection.properties and include it to hibernate.cfg.xml in form of

3条回答
  •  粉色の甜心
    2020-12-07 03:46

    You can do it programmatically.

    hibernate.cfg.xml should be as following.

    
        
        
            
                org.hibernate.transaction.JDBCTransactionFactory
            
        
    

    dbConnection.properties

    connection.driver_class=org.postgresql.Driver
    connection.username=postgres
    connection.password=postgres
    

    And when creating the SessionFactory you can do the following.

    Properties dbConnectionProperties = new Properties();
    try {
        dbConnectionProperties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("dbConnection.properties"));
    } catch(Exception e) {
        // Log
    }
    
    SessionFactory sessionFactory = new Configuration().mergeProperties(dbConnectionProperties).configure().buildSessionFactory();
    

提交回复
热议问题