Wednesday, April 8, 2009

Encrypting the Connection information in persistence.xml in JPA

Hi All,

I want to share my experience and the way I used to encrypt the connection related information in JavaEE applications.

I was working on JPA as a standalone ORM solution for my application. Please follow the steps I have explained below to remove the connection information from the persistence.xml

Step 1) Remove the Connection related properties from the persistence.xml file

persistence unit of the persistence.xml is "periodicManager"

Step 2) Create entityManager by injecting the properties as Map


ResourceBundle resBundle = ResourceBundle.getBundle("path/to/persistence");

Map persistenceMap = new HashMap();
Enumeration bundleKeys = resBundle.getKeys();
while(bundleKeys.hasMoreElements()){
String key = bundleKeys.nextElement();
String value = resBundle.getString(key);

persistenceMap.put(key, value);
}

EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("periodicManager", persistenceMap);

entityManager = entityManagerFactory.createEntityManager();

By this way we can remove the connection related information from the persistence.xml and injected into Persistence's createEntityManagerFactory.

Now, you can put the connection related information to the properties file. You can encrypt the properties file by using any encryptor program.

Cheers




No comments: