The Easiest Way To Access A Database in JAVA

Chelariu Andrei
The Fresh Writes
Published in
6 min readFeb 16, 2023

Comparison between Hibernate, JPA, EclipseLink, and Spring Data JPA

Photo by Tobias Fischer on Unsplash

What is ORM in Java?

ORM stands for Object-Relational Mapping, and it’s a technique used in Java and other programming languages to map the data stored in a relational database to objects in a programming language. The idea is to provide a convenient way to access and manipulate the data stored in the database, without having to write SQL code.

Popular JAVA ORM frameworks include:

  • Hibernate
  • Spring Data JPA
  • JPA

The easiest way To Mapping With A Database in JAVA depends on our requirements for our project, or what kind of database we would like to use.

Let’s discuss each other in more detail.

Overview: Java Persistence API (JPA)

Provides a specification for persisting, reading, and managing data from your Java object to relational tables in the database. This framework provides a convenient and consistent API for performing CRUD operations (Create, Read, Update, Delete) on the database and managing the relationships between objects. This can help to reduce the amount of code that needs to be written, and make the code more maintainable and easier to understand.

Hibernate vs JPA?

Hibernate is an implementation of the JPA, while JPA is a specification for ORM in Java. JPA defines a set of standard APIs for persisting data in a database using Java objects, while Hibernate is a specific implementation of those APIs. Hibernate has a more powerful architecture than JPA, as it allows developers to customize the ORM process.

Here’s a simple example of how you could persist a simple “Person” object to a database using both JPA and Hibernate:

JPA

@Entity
public class Person {

@Id
@GeneratedValue
private Long id;

private String firstName;

private String lastName;

// Getters and setters omitted for brevity
}

// Persisting an entity using JPA
EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistenceUnitName");
EntityManager em = emf.createEntityManager();

em.getTransaction().begin();
Person person = new Person();
person.setFirstName("John");
person.setLastName("Doe");
em.persist(person);
em.getTransaction().commit();

em.close();
emf.close();

Hibernate

@Entity
public class Person {

@Id
@GeneratedValue
private Long id;

private String firstName;

private String lastName;

// Getters and setters omitted for brevity
}

// Persisting an entity using Hibernate
SessionFactory sessionFactory = new Configuration()
.configure()
.buildSessionFactory();
Session session = sessionFactory.openSession();

session.beginTransaction();
Person person = new Person();
person.setFirstName("John");
person.setLastName("Doe");
session.save(person);
session.getTransaction().commit();

session.close();
sessionFactory.close();

As you can see, both JPA and Hibernate use similar annotations to mark a class as an entity, define a primary key, and specify the mapping of fields to columns in the database.

Spring Data JPA vs JPA?

Spring Data JPA is a framework, while JPA is a specification. Spring Data JPA is a default JPA implementation called Hibernate with the specification that is provided as part of the Spring Framework.

Here’s an example using JPA:

@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;

// Getters and setters ...
}

PersonDao class:

public class PersonDao {
private EntityManager em;

public PersonDao(EntityManager em) {
this.em = em;
}

public void save(Person person) {
em.getTransaction().begin();
em.persist(person);
em.getTransaction().commit();
}

public Person findById(Long id) {
return em.find(Person.class, id);
}
}

On the other hand, Spring Data JPA and more quickly to get ready because we will create just an interface and will call the implementation like below:

public interface PersonRepository extends JpaRepository<Person, Long> {
}

As you can see, using Spring Data JPA, you no longer need to write the DAO class that implements the persistence logic. The PersonRepository interface extends JpaRepository, which provides the Person entity’s basic CRUD operations (create, read, update, delete).

You can also use the PersonRepository to perform more complex operations by simply declaring methods with specific names and following a naming convention. Spring Data JPA will automatically generate the implementation for you.

As you can see, the quickest way to map a database in java is by using the Spring Data JPA framework.

Overview: Hibernate

Hibernate is an open-source object-relational mapping (ORM) framework for the Java programming language. The purpose of this framework is to relieve the developers from a significant amount of relational data, including managing transactions and converting data from an object representation to a relational representation.

Hibernate can be used with or without the Java Persistence API (JPA), but it is often used in conjunction with JPA to provide a complete solution for object-relational mapping and persistence in Java applications.

Advantages

  • This ORM framework simplifies the process of storing and retrieving data from a database.
  • Provides more performance and optimization features, such as lazy loading which can increase the performance of your application.
  • Provides a scalable solution for large-scale data persistence and management.

Disadvantages

  • Hibernate can be complex to use for complex relationships, such as inheritance or collections, which can lead to difficulties in mapping the object model to the relational model.
  • It can be verbose, especially when it comes to writing queries, which can make the code difficult to read and maintain.

Overview: Spring Data JPA

This framework brings in the concept of JPA Repositories, a set of Interfaces that defines query methods. You don’t need to write too many queries anymore. Spring Boot will automatically implement your repository interfaces, including custom finder methods, as you write them.

What you can create with Spring Data JPA:

  • Repository support: Spring Data JPA provides an interface-driven approach to data access. You can simply declare an interface that extends JpaRepository and get basic CRUD operations (Create, Read, Update, Delete)
  • Query creation: provides a mechanism for creating custom queries
  • Pagination and Sorting
  • Transactions: Spring Data JPA provides automatic transaction management, easy to perform with a simple annotation @Transaction

In other words, Spring Data JPA is a high-level framework that makes it easier to work with JPA and perform CRUD operations on a database.

Overview: EclipseLink

EclipseLink is a powerful object-relational mapping (ORM) tool that is part of the Eclipse Foundation’s enterprise Java tooling. It is an open source and a good way to start learning java. Isn’t easy as Spring Data JPA but you will be able to understand better what is happening inside an application.

Supports a lot of databases that you can choose such as Postgres, MySQL, and MariaDB. Offers helpful features such as lazy loading and a high-performance level and ensures your application’s scalability.

The downside is that they can require more setup and configuration than other ORM tools.

Example of a simple EclipseLink implementation:

EntityManagerFactory emf = Persistence.createEntityManagerFactory("default");
EntityManager em = emf.createEntityManager();

// clear
em.getTransaction()
.begin();
em.createQuery("DELETE FROM Employee ").executeUpdate();
em.getTransaction()
.commit();

Employee e1 = new Employee("Costel", "Daniel", "0742929245", 21, Departament.Marketing, 2100.0);
Employee e2 = new Employee("Daniel", "Costin", "0742929345", 26, Departament.IT, 4100.0);
Employee e3 = new Employee("Codrin", "Daniel", "0742929245", 41, Departament.HumanResource, 3100.0);

em.getTransaction()
.begin();
System.out.println("Saving your new employees");
em.persist(e1);
em.persist(e2);
em.persist(e3);

em.getTransaction()
.commit();

System.out.println("End");
}

Summary

If you are using JPA, you would have to write the necessary code to implement the persistence logic yourself. But with Spring Data JPA, much of the persistence logic is automatically implemented for you, so you can focus on writing the application’s business logic. That’s why Spring Data JPA is more popular among developers because they can focus on business logic and not write a lot of queries.

In conclusion, when you choose an ORM tool, it is important to consider the specific needs of your project, including the type of database you want to use and the complexity of your data model.

Done!

Stay tuned for more about the topic!

Thanks for reading!

--

--