Why and when you should use JPA?

Why and when you should use JPA?
Techiio-author
Written by Sagar RabidasFebruary 23, 2022
22 min read
Hibernate
2 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 2 VIEWS SHARE
Techiio-author
Sagar Rabidas

Software Developer

Today we will discuss - why and when you should use JPA?

Introduction of JPA:-

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.

Why and when JDBC was created:-

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:

  • A way to fetch objects directly from the query result set. As we have seen in the example above, we need to iterate the ReusltSet and extract the column values to set the Post object properties.
  • A transparent way to batch statements without having to rewrite the data access code when switching from the default non-batching mode to using batching.
  • support for optimistic locking
  • A pagination API that hides the underlying database-specific Top-N and Next-N query syntax

Why and when Hibernate was created:-

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.

Why and when was JPA created:-

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();

Advantages and disadvantages of using JPA and Hibernate:-

Advantages of using JPA and Hibernate:-

  • You can fetch entities or DTOs. You can even fetch hierarchical parent-child DTO projection.
  • You can enable JDBC batching without changing the data access code.
  • You have support for optimistic locking.
  • You have a pessimistic locking abstraction that’s independent of the underlying database-specific syntax so that you can acquire a READ and WRITE LOCK or even a SKIP LOCK.
  • You have a database-independent pagination API.
  • You can provide a list of values to an IN query clause, as explained in this article.
  • You can use a strongly consistent caching solution that allows you to offload the Primary node, which, for rea-write transactions, can only be called vertically.
  • You have built-in support for audit logging via Hibernate Envers.
  • You have built-in support for multitenancy.
  • You can generate an initial schema script from the entity mappings using the Hibernate hbm2ddl tool, which you can supply to an automatic schema migration tool, like Flyway.
  • Not only that you have the freedom of executing any native SQL query, but you can use the SqlResultSetMapping to transform the JDBC ResultSet to JPA entities or DTOs.

Disadvantages of using JPA and Hibernate:-

  • While getting started with JPA is very easy, becoming an expert requires a significant time investment because, besides reading its manual, you still have to learn how database systems work, the SQL standard as well as the specific SQL flavor used by your project relation database.
  • Some less-intuitive behaviors might surprise beginners, like the flush operation order.
  • The Criteria API is rather verbose, so you need to use a tool like Codota to write dynamic queries more easily.

JPA alternatives:-

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:

  • MyBatis, which is a very lightweight SQL query mapper framework.
  • QueryDSL, which allows you to build SQL, JPA, Lucene, and MongoDB queries dynamically.
  • jOOQ, which provides a Java metamodel for the underlying tables, stored procedures, and functions and allows you to build an SQL query dynamically using a very intuitive DSL and in a type-safe manner.

Conclusion:-

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.

Hibernate
JPA
JDBC
Java
2 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 2 VIEWS SHARE
Was this blog helpful?
techiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plan
You must be Logged in to comment
Code Block
Techiio-author
Sagar Rabidas
Software Developer
Techiio-followerTechiio-followerTechiio-followerTechiio-followerTechiio-follower
+8 more
300 Blog Posts
14 Discussion Threads
Trending Technologies
15
Software40
DevOps46
Frontend Development24
Backend Development20
Server Administration17
Linux Administration26
Data Center24
Sentry24
Terraform23
Ansible83
Docker70
Penetration Testing16
Kubernetes21
NGINX20
JenkinsX17
Techiio-logo

Techiio is on the journey to build an ocean of technical knowledge, scouring the emerging stars in process and proffering them to the corporate world.

Follow us on:

Subscribe to get latest updates

You can unsubscribe anytime from getting updates from us
Developed and maintained by Wikiance
Developed and maintained by Wikiance