1

I've this file hibernate.cfg.xml that I use to configure hibernate at sturtup.

<property name="hibernate.connection.username">dbUser</property>
<property name="hibernate.connection.password">1234</property>

I've a properties file that it's called config.properties that hold all other configurations used into the application.

How can I set "hibernate.connection.username" parameter from the properties file (config.properties) so I have only one file to edit?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Andrea Catania
  • 1,361
  • 3
  • 21
  • 37
  • [Are you searching for something like this ?](http://stackoverflow.com/questions/17939339/propertyplaceholderconfigurer-with-hibernate-cfg-xml) – Neeraj Jain Mar 18 '15 at 14:17
  • @NeerajJain that works when using an IoC and dependency injection framework like Spring (as shown in that link). In case you don't use it, you can do it with a little more effort. – Luiggi Mendoza Mar 18 '15 at 14:18
  • there is no way to set parameters from Java code during hibernate startup? – Andrea Catania Mar 18 '15 at 14:25
  • AFAIK the best way is to create a `DataSource` using Apache DBCP, C3P0, HikariCP or another vendor, and then follow the steps shown here: http://stackoverflow.com/q/4406935/1065197. Note that when you create your `DataSource` instance, you can apply the parameters from a properties file as you want/need. – Luiggi Mendoza Mar 18 '15 at 14:27
  • @LuiggiMendoza I've found that which work for me: configuration.setProperty( "hibernate.connection.username", "1234" ); What do you think about? – Andrea Catania Mar 18 '15 at 14:35
  • Post it as an answer then, but I don't recommend you using that approach. – Luiggi Mendoza Mar 18 '15 at 14:36

3 Answers3

0

It depends on the destination of the properties stored in config.properties

If they go in the java System properties, you can use them in your hibernate config like this :

<property name="hibernate.connection.password">${propertyName}</property>

If your properties go somewhere else, then I don't think hibernate will see them naturally...

0

The solution for me is that, Adding a properties at runtime into the configuration:

configuration.setProperty("hibernate.connection.username", Config.db.getUser());
Andrea Catania
  • 1,361
  • 3
  • 21
  • 37
0

I do it like that:

Map<String, Object> prop = new HashMap<String, Object>();

prop.put("hibernate.connection.username", "asdf");
prop.put("hibernate.connection.password", "xxx");


Persistence.createEntityManagerFactory(persistenceUnitName, prop);
griFlo
  • 2,084
  • 18
  • 28