JPA with Eclipse and MySQL: Using Java Configuration

The** Java Persistence API** is a standard specification for ORM (Object Relational Mapping) implementations. Also, it shows how to define a PLAIN OLD JAVA OBJECT (POJO) as an entity and how to manage entities with relations.

Key JPA Entities

**1.) **<strong>EntityManagerFactory</strong>: This is a factory class of EntityManager. It creates and manages multiple EntityManager instances.

**2.) **<strong>EntityManger</strong>: This interface manages the persistence operations on entities.

**3.) **<strong>Entity</strong>: Entities are the persistence objects, stores as records in the database.

**4.) **<strong>EntityTransaction</strong>: It has a one-to-one relationship with EntityManager. For each EntityManager, operations are maintained by EntityTransaction class.

**5.) **<strong>Persistence</strong>: This class contains static methods used to obtain a EntityManagerFactory instance.

**6.) **<strong>Query</strong>: This interface is implemented by each JPA vendor to obtain relational objects that meet the criteria.

Now, let us start our JPA implementations with an example:

Required Maven dependencies:

<dependencies>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.7.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
</dependencies>

Here, to achieve persistence in the application, we need to introduce the persistence.xml, which has to be located in the META-INF directory in the project classpath.

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="JPATest"
transaction-type="RESOURCE_LOCAL">
<class><!-- Entity Class Name --></class>
</persistence-unit>
</persistence>

Here, the persistence unit name must be unique. Also, we can add multiple persistence-units for different units. The transaction type for this persistence unit is RESOURCE_LOCAL.

There are two types of transactions:

  • JTA: The transactions will be managed by the Application Server
  • RESOURCE_LOCAL: The transaction will be managed by the JPA Provider Implementation in use.

Also, specify the class name for entities in this configuration file. There is one more configuration used for the database connection. But for dynamic configuration of database connection, we add that configuration in Java code instead of this XML file.

EntityManager:

public class JpaEntityManager {
private EntityManagerFactory emFactoryObj;
private final String PERSISTENCE_UNIT_NAME = "JPATest";
private final Map<String, String> properties=new HashMap<String, String>();


// This Method Is Used To Retrieve The 'EntityManager' Object
public EntityManager getEntityManager() {

String url = String.format("%s/%s", DBConstants.DB_HOST, DBConstants.DB_NAME);

properties.put("javax.persistence.jdbc.driver",DBConstants.DB_DRIVER);
properties.put("javax.persistence.jdbc.url", url);
properties.put("javax.persistence.jdbc.user", DBConstants.DB_USER);
properties.put("javax.persistence.jdbc.password",DBConstants.DB_PASSWORD);
properties.put("useSSL", DBConstants.DB_USE_SSL);
properties.put("requireSSL", DBConstants.DB_REQUIRED_SSL);
properties.put("serverTimezone",DBConstants.DB_SERVER_TIMEZONE);

emFactoryObj = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME,properties);

return emFactoryObj.createEntityManager();
}
}

Here, you have to add your database related configuration like drive class name, hostname, database name, username, password, etc.

Database schema:

CREATE TABLE user (
  id INTEGER NOT NULL,
  name VARCHAR(255) NOT NULL,  
  age VARCHAR(100) NOT NULL,
  PRIMARY KEY(id)
);

Entity:

Here are some annotations used for JPA implementation.

1.) @Entity: to mark the java class as an entity.

2.) @Table: to specify the table to which this entity class maps.

3.) @Id: to identify a row uniquely (JPA Primary Key).

4.) @Column: to specify the mapped column for a persistent property or field.

**5. **<strong>JPARepository</strong>: used to perform database-related operations.

public class JpaRepository<T, ID> implements AutoCloseable {

private final Class<T> typeParameterClass;
protected EntityManager entityManager;

public JpaRepository(Class<T> typeParameterClass) {
JpaEntityManager dbEntityManager = new JpaEntityManager();
entityManager = dbEntityManager.getEntityManager();
this.typeParameterClass = typeParameterClass;
}
/**
 * Save an entity.
 * @param entity
 * @return the saved entity
 */
public <S extends T> S save(S entity) {
entityManager.getTransaction().begin();
entityManager.persist(entity);
entityManager.getTransaction().commit();
return entity;
}
/**
 * merge an entity.
 *
 * @param entity
 * @return the saved entity
 */
public <S extends T> S merge(S entity) {
entityManager.getTransaction().begin();
entityManager.merge(entity);
entityManager.getTransaction().commit();
return entity;
}
/**
 * Delete an entity
 * 
 * @param id
 */
public void delete(ID id) {
entityManager.remove(id);
}
/**
 * Returns a reference to the entity with the given identifier.
 * 
 * @param id
 * @return
 */
public T findById(ID id) {
T t = entityManager.find(typeParameterClass, id);
return t;
}
/**
 * get single result
 * 
 * @param q
 * @return
 */
public Optional<T> getSingleResult(CriteriaQuery<T> q) {

try {
return Optional.ofNullable(entityManager.createQuery(q).getSingleResult());
} catch (RuntimeException e) {
return Optional.empty();
}
}
/**
 * get single result
 * 
 * @param q
 * @return
 */
public Optional<List<T>> getResultList(CriteriaQuery<T> q) {
try {
return Optional.ofNullable(entityManager.createQuery(q).getResultList());
} catch (RuntimeException e) {
return Optional.empty();
}
}
/**
 * used to close entity manager obj
 */
public void close() {
entityManager.clear();
entityManager.close();
}
}

You can also use JPA Criteria API queries, which provide an alternative way for defining JPA queries and is mainly useful for building dynamic queries whose exact structure is only known at runtime.

Now, all configuration is done. So, let us start to test this application.

public class JPADemo {

public static void main(String[] args) {
User user=new User();
user.setId(1);
user.setAge(20);
user.setName("Abc");

try(JpaRepository userJpaRepository=new JpaRepository<BlenderMaster, Long>(BlenderMaster.class)){
userJpaRepository.save(user);
}catch (Exception e) {
e.printStackTrace();
}
}
}

Here, we added the JPA Repository resource in a try catch, so resource will be closed automatically after use. After running this application, one new user entry will be added in the MySQL database.

Thanks For Visiting, Keep Visiting. If you liked this post, share it with all of your programming buddies!

Further reading

Java Programming Masterclass for Software Developers

JSP, Servlets and JDBC for Beginners: Build a Database App

Java 8 New Features In Simple Way

Java In-Depth: Become a Complete Java Engineer!

Java for Absolute Beginners

Java Programming for Complete Beginners - Learn in 250 Steps

Learn Java Programming Crash Course

Apache Spark for Java Developers

#java #mysql #jpa #maven #database #api #web-development

JPA with Eclipse and MySQL: Using Java Configuration
28.10 GEEK