0

The problem with hibernate is, you need to put the database info (username/pw etc) in an xml file. However, if you deploy your app on Amazon web services, e.g on Beanstalk, you get the db info passed in via System.getProperty("RDS_DATABASE_USER"), etc. The advantage is, if more instances of your app are created, the db info is passed on automatically, without having to manually edit config files.

Is there a way to pass the db info to hibernate at runtime? If not, is there another good ORM library for java, to which you can pass this info at runtime? I'm using MySQL.

Ali
  • 261,656
  • 265
  • 575
  • 769

1 Answers1

2

As a matter of fact, the method PersistenceUtil.createEntityManagerFactory allows you to provide a properties map. Using this map you can provide the user name and password in dynamic way.

How you do this may well depend on what specific frameworks you are using.

Based on the tags in your question it is not clear if you are using Hibernate or if you are using OpenJPA.

The Open JPA documentation in the section Obtaining an EntityManagerFactory provides the list of properties you could use.

Map<String,String> properties = new HashMap<>();
properties.put("openjpa.ConnectionUserName", "userName");
properties.put("openjpa.ConnectionPassword", "password");
EntityManagerFactory emf = Persistence.createEntityManagerFactory("MyPersistenceUnit",properties);

Hibernate supports a similar set of properties. Most probably you already have them in your persistence.xml file.

Some dependency injection frameworks, like Spring, don't even require a persistence.xml file and can read such properties dynamically from some other places, like environment variables.

Edwin Dalorzo
  • 76,803
  • 25
  • 144
  • 205
  • I only put openJPA to indicate that I was open to using it as an alternative if this wasn't possible with Hibernate. Can this method of passing in properties, be used with Hibernate, or does it only work with OpenJPA? – Ali Feb 03 '14 at 03:06
  • @ClickUpvote It works with all JPA implementations, like hibernate, eclipse link and open JPA. – Edwin Dalorzo Feb 03 '14 at 13:02
  • If you could add a sample of how it would be used with hibernate, I can accept – Ali Feb 03 '14 at 21:57
  • @ClickUpvote For somebody with 27k reputation, I am surprised on your request. You can see an example of Hibernate properties in this another answer: http://stackoverflow.com/a/18743562/697630. I am pretty sure you can figure out the rest. – Edwin Dalorzo Feb 04 '14 at 18:53
  • That one is using an XML file, what I'm looking for is a way to pass it on at runtime. I've not worked with any ORM before. – Ali Feb 05 '14 at 04:37
  • @ClickUpvote Just use my example with the properties of the other question example. – Edwin Dalorzo Feb 05 '14 at 04:39
  • I would still use `Persistence.createEntityManagerFactory`? That will work with Hibernate? – Ali Feb 05 '14 at 04:40