This Article is written considering EclipseLink as JPA provider, MySql as Database.

When instantiating EntityManagerFactory there are 2 APIs provided by javax.persistence.Persistence

createEntityManagerFactory(String persistenceUnitName) and the overloaded method

createEntityManagerFactory(String persistenceUnitName, Map properties)

The connection properties to the physical database can be provided in the persistence.xml

as in :

Here we are connecting to mysql database running on localhost:3306

Then EntityManagerFactory can be instantited by passing the persistence unit name, as in :

Persistence.createEntityManagerFactory(“Eclipselink_JPA”)

2. We can also provide the same details in the map that we paas to the overloaded createEntityManagerFactory method.

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

props.put(“javax.persistence.jdbc.url” , “jdbc:mysql://localhost:3306/jpadb”);

props.put(“javax.persistence.jdbc.user” , “root”);

props.put(“javax.persistence.jdbc.password” , “password”);

props.put(“javax.persistence.jdbc.driver” , “com.mysql.jdbc.Driver”); EntityManagerFactory emfactory = Persistence.createEntityManagerFactory(“Eclipselink_JPA”, props);



3. Another way to connect to physical database is by creating a javax.sql.DataSource object.

https://docs.oracle.com/javase/7/docs/api/javax/sql/DataSource.html

Normally this is preferred way of connecting to a database as this can be externalized from the code.

The DataSource interface is implemented by a driver vendor.

As per the documentation, This is an alternative to the DriverManager facility, a DataSource object is the preferred means of getting a connection. An object that implements the DataSource interface will typically be registered with a naming service based on the Java Naming and Directory (JNDI) API.

In the code we do a JNDI lookup and get the DataSource object.

This DataSource object is then added in the properties map and is used to create EntityManagerFactory as :

MysqlDataSource ds = new MysqlDataSource();

ds.setURL(“jdbc:mysql://localhost:3306/jpadb”);

ds.setUser(“root”);

ds.setPassword(“password”);



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

props.put(“javax.persistence.nonJtaDataSource”, ds); EntityManagerFactory emfactory = Persistence.createEntityManagerFactory(“Eclipselink_JPA”, props);

In the above code we are creating MysqlDataSource object which extends javax.sql.DataSource object.

In the real world scenario this DataSource is binded to JNDI registry when we create database schema and bind it to a named datasource.

In the code we access this DataSource via JNDI lookup.