DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Navigating NoSQL: A Pragmatic Approach for Java Developers
  • Useful System Table Queries in Relational Databases
  • Introducing Graph Concepts in Java With Eclipse JNoSQL
  • Simplify NoSQL Database Integration in Java With Eclipse JNoSQL 1.1.3

Trending

  • How SaaS Architectures Break at Scale — and the Engineering Decisions That Prevent It
  • When Snowflake Lies to You: Understanding False Failures in dbt Pipelines
  • Chaos Engineering Has a Blind Spot. Agentic AI Lives in It.
  • Spring AI Advisors: Chat Memory, Token Tracking, and Message Logging
  1. DZone
  2. Data Engineering
  3. Databases
  4. JPA With Eclipse and MySQL Using Java Configuration

JPA With Eclipse and MySQL Using Java Configuration

Learn more about the Java Persistence API and how to configure it with EclipseLink and MySQL.

By 
Riddhi Parkhiya user avatar
Riddhi Parkhiya
·
Jul. 15, 19 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
32.1K Views

Join the DZone community and get the full member experience.

Join For Free

In this article, we will discuss the Java persistence API configuration with EclipseLink and MySQL.

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.) EntityManagerFactory: This is a factory class of EntityManager. It creates and manages multiple EntityManager instances.

2.) EntityManger: This interface manages the persistence operations on entities.

3.) Entity: Entities are the persistence objects, stores as records in the database.

4.) EntityTransaction: It has a one-to-one relationship with EntityManager. For each EntityManager, operations are maintained by EntityTransaction class.
5.) Persistence: This class contains static methods used to obtain a EntityManagerFactory instance.
6.) Query: 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. JPARepository: 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.

Database Relational database Java (programming language) MySQL Java Persistence API Eclipse

Opinions expressed by DZone contributors are their own.

Related

  • Navigating NoSQL: A Pragmatic Approach for Java Developers
  • Useful System Table Queries in Relational Databases
  • Introducing Graph Concepts in Java With Eclipse JNoSQL
  • Simplify NoSQL Database Integration in Java With Eclipse JNoSQL 1.1.3

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook