سؤال

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.

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top