For the past 10 or so years, JPA has been one of the most popular ways of accessing a database within the Java ecosystem. Even if you haven’t heard of JPA directly, there is a high likelihood that you’ve heard of or even used one of the most popular implementations of the JPA API - Hibernate.

The reason why JPA is so popular is no secret - most of the inconveniences are abstracted from the user, making the API very intuitive to use. Let’s say that in some random database exists a table called person with the following structure:

To represent said table via JPA, users would typically create a class called Person which looks like this:

Once this initial setup is finished, users can use the EntityManager to create and execute queries. Let’s say we wanted to retrieve information about a person with the id of 10. With JPA we could do something like this:

I consider this to be a very efficient approach considering most of the heavy lifting is done for us. But not everything is sunshine and rainbows. Since we’re creating queries using raw SQL, syntax errors are inevitable most of the time.

To combat this, a type-safe way of creating queries was introduced in JPA 2.0, named the Criteria API. Let’s see how we can recreate the query above using the Criteria API:

#java #database #tutorial #hibernate #jpa #jpastreamer

How JPAstreamer Can Help You Write Type-Safe Hibernate Code
1.85 GEEK