Spring Data JPA

Spring Data JPA

JPA

Java Persistence API (JPA) is a Java Specification for Object Relational Mapping (ORM). It provides a high-level abstraction layer for database access. JPA allows us to use POJOs (Plain Old Java Objects) & provides a standard set of APIs for performing common Database Operations with ease.

Features of JPA

  • Simplified ORM: JPA simplifies ORM by reducing the need for writing Complex Queries & Iterating over Result Sets. It automatically handles the Database Operations, making it easy for the app to Create, Retrieve & Manipulate Data.
  • Database Independent: JPA abstracts the database details by exposing it's set of APIs. In this way, it's really easy to use different databases without making any Major changes to the Code, making the code much more Portable & Flexible.
  • Easy CRUD Operations: JPA provides common CRUD operations in form of Methods so, we just need to utilize them using Objects. JPA handles the task of converting these object changes & method calls into Database Operations.
  • Simple Queries: JPA provides a powerful mechanism for writing Complex Queries called JPQL (Java Persistent Query language). JPQL is similar to SQL but instead of working with Tables we work with Java Objects.
  • Caching & Performance Optimization: JPA incorporates caching mechanisms to improve performance by reducing number of Database Calls.

How to use JPA

As mentioned above, JPA is a Java Specification hence, we need to use an Implementation of JPA like: Hibernate, EclipseLink, Spring Data JPA, etc.

All JPA Implementations require us to define Entity classes that represent Database tables. We use JPA Annotations to specify the mapping details for each Entity & the corresponding Database Table.

JPA Automatically generates the APIs for performing operations on the Database. We can use EntityManager, a core interface in JPA, to manage Entity Instances, perform operations & execute queries.

Spring Data JPA

Spring Data JPA is a powerful Library that provides a high-level abstraction on top of JPA. It combines JPA's ORM with the ease & flexibility of Spring Framework.

Spring Data JPA allows us to use expressive Methods that simplify the task of performing common database operations. It reduces the Code complexity by reducing Boilerplate Code.

Features of Spring Data JPA

  • Repository: Repository is an Interface using which we can define a set of methods for interacting with the database. Repository methods encapsulate common CRUD operations as well as Complex Queries.
  • Automatic Query Generation: Spring Data JPA uses the method Naming Convention & Annotations to automatically generate Database Queries. The Queries are generated based on Method Signature. By using certain keywords in the Methods name, we can define database operations like: findByName, here findBy tells Spring to Retrieve Data & use name field of the Entity to filter. Spring Data JPA will automatically generate a Query with where clause. For complex functionality, we can pass a JPQL Query using @Query Annotation & map the method parameters to it using @Param.
  • Pagination & Sorting: Spring Data JPA provides built-in support for pagination, using which we can retrieve data in chunks. We can specify the Page Size & Sorting Criteria.

Using Spring Data JPA

We are going to use Spring Data JPA to get access to Products.

  • Add Required Dependencies in the Project. Preferably using Maven or Gradle.
  • Create Product Entity in a POJO as shown below:

package com.shivangam.ProductManagement

import jakarta.persistence.*;

@Entity
@Table(name = "product")
public class Product {
? ? @Id
? ? @GeneratedValue(strategy = GenerationType.IDENTITY)
? ? private int id;
? ? private String name;
? ? private String type;

? ? public Product() {
? ? }
? ? public Product(String name, String type, String place, int warranty) {
? ? ? ? this.name = name;
? ? ? ? this.type = type;
? ? ? ? this.place = place;
? ? ? ? this.warranty = warranty;
? ? }

? ? public int getId() {
? ? ? ? return id;
? ? }
? ? public void setId(int id) {
? ? ? ? this.id = id;
? ? }

? ? public String getName() {
? ? ? ? return name;
? ? }
? ? public void setName(String name) {
? ? ? ? this.name = name;
? ? }

? ? public String getType() {
? ? ? ? return type;
? ? }
? ? public void setType(String type) {
? ? ? ? this.type = type;
? ? }
}        

  • In the code above, @Entity is used to define that this class is an Entity & it will be persisted to a Database. @Table is used to describe details of the Database Table with which the Class needs to be mapped.@Id is being used to mark id as the Primary Key. @GeneratedValue is used with @Id to describe how the id should be generated. GenerationType.IDENTITY is one of the strategies used by @GeneratedValue IDENTITY relies on Database's Auto Increment feature.
  • Create a Repository for the Products

package com.shivangam.ProductManagement

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface ProductDB extends JpaRepository<Product, Integer> {
? ? Product findByNameIgnoreCase(String name);

? ? @Query("SELECT p FROM Product p WHERE LOWER(p.name) LIKE LOWER(concat('%', :text, '%')) OR LOWER(p.type) LIKE LOWER(concat('%', :text, '%'))")
? ? List<Product> findAllByText(@Param("text") String text);
}        

  • In the code above, @Repository is a specialized version of @Component it indicates that the interface is a Data Repository & it is responsible for performing database operations. It also allows Spring Framework to easily Dependency Inject it into the Code. JpaRepository is an interface that offers a set of operations that an entity can perform. It allows us to define operation simply with the use of findBy, save, delete, etc.
  • In the first method, we are defining the operation just using Method Naming. It describes: find a Product By using the Name property of the entity for Filter criteria & IgnoreCase. Spring Data JPA will automatically generate a query that uses the name parameter to get all products with that name, Case-Insensitively.
  • For the second method, we needed a special functionality, so using @Query we're passing a Custom JPQL Query. In the Query we require access to text so, we'll use @Param("text") to define that the parameter text should be injected into the custom query in-place of :text.

Day 3 Challenge

Challenge

Continue development of Product Management App by implementing it using Maven, Spring Boot, Spring Data JPA & PostgreSQL.

Solution

GitHub Repo README includes the Explanation of My Solutions.

Thank You, Navin Reddy , for the 10-Day Challenge.

#10daychallenge #day3 #java #programming #learning #springboot

要查看或添加评论,请登录

Shivangam Soni的更多文章

  • Modern JAVA Features

    Modern JAVA Features

    Ever since JAVA 8 there have been plenty of Regular changes to the Language. Many of these Changes are targeted towards…

  • Java Annotation: What, Why & How?

    Java Annotation: What, Why & How?

    Java Annotation Java Annotations are a way for us to provide Metadata or Additional Instructions about the Code…

    1 条评论
  • Java Reflection API & How Spring uses Reflection.

    Java Reflection API & How Spring uses Reflection.

    Reflection API Java Reflection API allows us to examine a class's behavior at Run-Time. It also allows us to manipulate…

  • Java Stream API & Functional Interface

    Java Stream API & Functional Interface

    Stream API Stream API was added in JAVA 8 & it has provided a much better way of working with Collections. It provides…

  • Recursion & Memoization

    Recursion & Memoization

    Iteration I think it's important to understand Iteration to fully understand Recursion. Iteration is a Programming…

    2 条评论

社区洞察

其他会员也浏览了