Software Developer
In case you are questioning why and while you ought to use JPA or hibernate, then this newsletter goes to offer you an answer to this very common question. Due to the fact I’ve visible, this question asked very frequently at the /r/java Reddit channel, I decided that it’s worth writing an in-intensity answer approximately the strengths and weaknesses of JPA and hibernate.
Although JPA has been fashionable because it became first launched in 2006, it’s no longer the most effective way you could enforce a records get right of entry to layer the use of java. We're going to talk about the advantages and disadvantages of the use of JPA or some other famous alternatives.
In 1997, Java 1.1 introduced the JDBC (Java Database Connectivity) API, which was very revolutionary for its time since it was offering the possibility of writing the data access layer once using a set of interfaces and running it on any relational database that implements the JDBC API without needing to change your application code.
The JDBC API offered a Connection interface to control the transaction boundaries and create simple SQL statements via the Statement API or prepared statements that allow you to bind parameter values via the PreparedStatement API.
So, assuming we have a post database table and we want to insert 100 rows, here’s how we could achieve this goal with JDBC:
int postCount = 100;
int batchSize = 50;
try (PreparedStatement postStatement = connection.prepareStatement("""
INSERT INTO post (
id,
title
)
VALUES (
?,
?
)
"""
)) {
for (int i = 1; i <= postCount; i++) {
if (i % batchSize == 0) {
postStatement.executeBatch();
}
int index = 0;
postStatement.setLong(
++index,
i
);
postStatement.setString(
++index,
String.format(
"High-Performance Java Persistence, review no. %1$d",
i
)
);
postStatement.addBatch();
}
postStatement.executeBatch();
} catch (SQLException e) {
fail(e.getMessage());
}
Even as we took the benefit of multi-line textual content blocks and try-with-assets blocks to cast off the prepared statement near the name, the implementation continues to be very verbose. Observe that the bind parameters start from 1, not zero as you might be used to from different famous APIs.
To fetch the first 10 rows, we may want to want to run an sq. Query thru the prepared statement, to be able to return a resultset representing the desk-based query result. However, since applications use hierarchical structures, like JSON or DTOs to represent parent-child associations, most applications needed to transform the JDBC ResultSet to a different format in the data access layer, as illustrated by the following example:
int maxResults = 10;
List<Post> posts = new ArrayList<>();
try (PreparedStatement preparedStatement = connection.prepareStatement("""
SELECT
p.id AS id,
p.title AS title
FROM post p
ORDER BY p.id
LIMIT ?
"""
)) {
preparedStatement.setInt(1, maxResults);
try (ResultSet resultSet = preparedStatement.executeQuery()) {
while (resultSet.next()) {
int index = 0;
posts.add(
new Post()
.setId(resultSet.getLong(++index))
.setTitle(resultSet.getString(++index))
);
}
}
} catch (SQLException e) {
fail(e.getMessage());
}
Again, this is the nicest way we could write this with JDBC as we’re using Text Blocks, try-with-resources, and a Fluent-style API to build the Post objects.
Nevertheless, the JDBC API is still very verbose and, more importantly, lacks many features that are required when implementing a modern data access layer, like:
In 1999, Sun released J2EE (Java Enterprise Edition), which offered an alternative to JDBC, called Entity Beans.
However, in view that entity beans had been notoriously slow, overcomplicated, and cumbersome to apply, in 2001, Gavin king decided to create an ORM framework that would map database tables to POJOs (undeniable vintage java objects), and that’s how to hibernate become born.
Being extra light-weight than entity beans and much less verbose than JDBC, hibernate grew an increasing number of famous, and it soon became the most popular java staying power framework, triumphing overdo, iBatis, oracle TopLink, and apache cayenne.
Getting to know from the hibernate venture success, the java ee platform decided to standardize the way hibernate and oracle TopLink, and that’s how JPA turned into born.
Jpa is the simplest specification and cannot be used on its personal, providing the most effective set of interfaces that outline the same old staying power API, that's applied by using a JPA provider, like hibernate, EclipseLink, or open JPA.
When using JPA, you need to define the mapping between a database table and its associated Java entity object:
@Entity
@Table(name = "post")
public class Post {
@Id
private Long id;
private String title;
public Long getId() {
return id;
}
public Post setId(Long id) {
this.id = id;
return this;
}
public String getTitle() {
return title;
}
public Post setTitle(String title) {
this.title = title;
return this;
}
}
Afterward, we can rewrite the previous example which saved 100 post records looks like this:
for (long i = 1; i <= postCount; i++) {
entityManager.persist(
new Post()
.setId(i)
.setTitle(
String.format(
"High-Performance Java Persistence, review no. %1$d",
i
)
)
);
}
To enable JDBC batch inserts, we just have to provide a single configuration property:
<property name="hibernate.jdbc.batch_size" value="50"/>
Once this property is provided, Hibernate can automatically switch from non-batching to batching without needing any data access code change.
And, to fetch the first 10 post rows, we can execute the following JPQL query:
int maxResults = 10;
List<Post> posts = entityManager.createQuery("""
select p
from post p
order by p.id
""", Post.class)
.setMaxResults(maxResults)
.getResultList();
One of the greatest things about the Java ecosystem is the abundance of high-quality frameworks. If JPA and Hibernate are not a good fit for your use case, you can use any of the following frameworks:
In this text, we saw why JPA became created and when you must use it. While JPA brings many benefits, you've got many different top-notch alternatives to use if JPA and hibernate don’t work excellently in your contemporary software necessities.
And, occasionally, as I defined in this unfastened sample of my excessive-overall performance java staying power ebook, you mustn’t even select between JPA or different frameworks. You can effortlessly integrate JPA with a framework like JOOQ to get the first class of each world.