SlideShare a Scribd company logo
1 of 23
Spring Data JPA
Pagination and Sorting
 Pagination is often helpful when we have a large
dataset and we want to present it to the user in
smaller chunks.
 Also, we often need to sort that data by some criteria
while paging.
 While dealing with large amount of data the lazy
processing is often essential. Even if a service returns
a huge amount of data the consumer is less likely
using it.
 Consider a shopping website, where customer
searches for a product and the website has
thousands of products to display. Fetching thousands
of products and displaying it on a web page will be
very time consuming. In most of the cases the
customer may not even look at all of the products.
contd
 For such cases a technique called as Pagination is used. Only a
small subset of products (page) is displayed at first and customer
can ask to see the next subset (page) and so on. This is called
as Pagination.
 Pagination allows the users to see a small portion of data at a
time (a page), and sorting allows the users to view the data in a
more organized way. Both paging and sorting help the users
consume information more easily and conveniently.
Query Approaches
Spring Data by default provides the following query
methods through its interface:
 findAll //Returns all entities
 findById(ID id) //Returns the entity depending upon
given id
 What if one wants to query customer records based on the
customer's address?
 How does Spring support this scenario?
 Spring supports these kinds of scenarios using the
following approaches:
 Query creation based on the method name.
 Query creation using @NamedQuery: JPA named queries
through a naming convention.
 Query creation using @Query: annotate the query method
with @Query.
 Query method names are derived by combining the
property name of an entity with supported keywords such
as "findBy", "getBy", "readBy" or "queryBy".
findBy <DataMember><Op>
Customer class
public class Customer {
private Long phoneNumber;
private String name;
private Integer age;
private Character gender;
private String address;
private Integer planId;
//getters and setters
}
To query a record based on the address using query creation by the
method name, the following method has to be added to the
CustomerRepository interface.
interface CustomerRepository extends JpaRepository<Customer, Long>
{
Customer findByAddress(String address); // method declared
}
contd
 If a query is provided using more than one
approach in an application. What is the default
precedence given by the Spring?
Following is the order of default precedence:
 @Query always takes high precedence over
other options
 @NameQuery
 findBy methods
 @Query Annotation is used for defining custom
queries in Spring Data JPA. When you are unable
to use the query methods to execute database
operations then you can use @Query to write a
more flexible query to fetch data.
 @Query Annotation supports both JPQL and
native SQL queries.
JPQL
JPQL is an object-oriented query language that is used to
perform database operations on persistent entities.
Instead of a database table, JPQL uses the entity object
model to operate the SQL queries. Here, the role of JPA
is to transform JPQL into SQL. Thus, it provides an easy
platform for developers to handle SQL tasks.
Features:
 The features of JPQL are that it can:
 perform join operations
 update and delete data in a bulk
 perform an aggregate function with sorting and grouping
clauses
 provide both single and multiple value result types
JPQL
 @Query("SELECT * FROM Student ORDER BY
age") Optional<Student>
findSortedStudentByAge();
Native Query
 If you want to use this native query in the Spring
Boot project then we have to take the help
of @Query Annotation and we have to set an
attribute nativeQuery=true in Query annotation
to mark the query as native.
@Query(nativeQuery = true, value = "SELECT *
FROM Student ORDER BY age") Optional<Student>
findSortedStudentByAge();
Creating Queries using JPQL:
JPQL provides two methods that can be used to
perform database operations. They are: -
Query createQuery(String name) -
The createQuery() method of EntityManager
interface is used to create an instance of the
Hibernate Query interface for executing JPQL
statement. This method creates dynamic queries
that can be defined within business logic.
 Fetching all the Customer names:
Query query = em.createQuery("Select c.name from
CustomerEntity c");
NamedQuery
 Named queries are one of the core concepts in
JPA. They enable you to declare a query in your
persistence layer and reference it in your
business code. That makes it easy to reuse an
existing query. It also enables you to separate the
definition of your query from your business code.
 Named queries make it easier to maintain and
reuse complex database queries by giving them a
recognizable name. Instead of writing the entire
query every time you need to use it, you can refer
to it by its name. This improves code readability,
maintainability, and reduces redundancy.
NamedQuery
Query createNamedQuery(String name) -
The createNamedQuery() method of EntityManager interface is
used to
create an instance of the Hibernate Query interface for executing
named
queries. This method is used to create static queries that can be
defined in
the entity class.
Ex:
@NamedQuery(name = "getAll" , query = "Select c from
CustomerEntity s")
 In an enterprise application, a transaction is a
sequence of actions performed by the application
that together pipelined to perform a single
operation. For example, booking a flight ticket is
also a transaction where the end user has to
enter his information and then make a payment to
book the ticket.
Why Do We Need Transaction
Management?
 Let’s understand transactions with the above
example, if a user has entered his information the
user’s information gets stored in the user_info
table. Now, to book a ticket he does an online
payment and due to some reason(system failure)
the payment has been canceled so, the ticket is
not booked for him. But, the problem is that his
information gets stored on the user_info table. On
a large scale, more than thousands of these
things happen within a single day. So, it is not
good practice to store a single action of the
transaction
contd
 To overcome these problems, spring provides
transaction management, which uses annotation
to handle these issues. In such a scenario, spring
stores the user information in temporary memory
and then checks for payment information if the
payment is successful then it will complete the
transaction otherwise it will roll back the
transaction and the user information does not
gets stored in the database.
EX:
Programmatic vs. Declarative
 Spring supports two types of transaction
management −
 Programmatic transaction management − This
means that you have to manage the transaction
with the help of programming. That gives you
extreme flexibility, but it is difficult to maintain.
 Declarative transaction management − This
means you separate transaction management
from the business code. You only use annotations
or XML-based configuration to manage the
transactions.
contd
 @Transactional annotation, which provides broad
support for transaction management and allows
developers to concentrate on business logic
rather than worrying about data integrity in the
event of system failures
 Spring Data JPA already provides many solutions
that allow us to query data easier such as Query
Method, Query Method, or four repository
 interface(JpaRepository, PagingAndSortingRepos
itory, CrudRepository, Repository). These features
are powerful, which help me a lot when building
an application with Spring Data JPA. But a lot of
time we still need to custom query or method to
meet expectations or requirements.
Spring Data JPA in detail with spring boot

More Related Content

Similar to Spring Data JPA in detail with spring boot

professional fuzzy type-ahead rummage around in xml type-ahead search techni...
professional fuzzy type-ahead rummage around in xml  type-ahead search techni...professional fuzzy type-ahead rummage around in xml  type-ahead search techni...
professional fuzzy type-ahead rummage around in xml type-ahead search techni...Kumar Goud
 
Intention Oriented Model Interaction
Intention Oriented Model InteractionIntention Oriented Model Interaction
Intention Oriented Model InteractionYasir Karam
 
What is struts_en
What is struts_enWhat is struts_en
What is struts_entechbed
 
Spring Transaction
Spring TransactionSpring Transaction
Spring Transactionpatinijava
 
PATTERNS07 - Data Representation in C#
PATTERNS07 - Data Representation in C#PATTERNS07 - Data Representation in C#
PATTERNS07 - Data Representation in C#Michael Heron
 
Best practices in using Salesforce Metadata API
Best practices in using Salesforce Metadata APIBest practices in using Salesforce Metadata API
Best practices in using Salesforce Metadata APISanchit Dua
 
Dataware housing
Dataware housingDataware housing
Dataware housingwork
 
Sql storeprocedure
Sql storeprocedureSql storeprocedure
Sql storeprocedureftz 420
 
A Data Warehouse And Business Intelligence Application
A Data Warehouse And Business Intelligence ApplicationA Data Warehouse And Business Intelligence Application
A Data Warehouse And Business Intelligence ApplicationKate Subramanian
 
SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015Pushkar Chivate
 
Best practices in using Salesforce Metadata API
Best practices in using Salesforce Metadata APIBest practices in using Salesforce Metadata API
Best practices in using Salesforce Metadata APISanchit Dua
 
Unit-IV-Introduction to Data Warehousing .pptx
Unit-IV-Introduction to Data Warehousing .pptxUnit-IV-Introduction to Data Warehousing .pptx
Unit-IV-Introduction to Data Warehousing .pptxHarsha Patel
 
Data Models Breakout Session
Data Models Breakout SessionData Models Breakout Session
Data Models Breakout SessionSplunk
 
Retail products - machine learning recommendation engine
Retail products   - machine learning recommendation engineRetail products   - machine learning recommendation engine
Retail products - machine learning recommendation enginehkbhadraa
 
Cognos framework manager
Cognos framework managerCognos framework manager
Cognos framework managermaxonlinetr
 
Murach : How to work with session state and cookies
Murach : How to work with session state and cookiesMurach : How to work with session state and cookies
Murach : How to work with session state and cookiesMahmoudOHassouna
 
Data Seeding via Parameterized API Requests
Data Seeding via Parameterized API RequestsData Seeding via Parameterized API Requests
Data Seeding via Parameterized API RequestsRapidValue
 

Similar to Spring Data JPA in detail with spring boot (20)

V33119122
V33119122V33119122
V33119122
 
professional fuzzy type-ahead rummage around in xml type-ahead search techni...
professional fuzzy type-ahead rummage around in xml  type-ahead search techni...professional fuzzy type-ahead rummage around in xml  type-ahead search techni...
professional fuzzy type-ahead rummage around in xml type-ahead search techni...
 
Intention Oriented Model Interaction
Intention Oriented Model InteractionIntention Oriented Model Interaction
Intention Oriented Model Interaction
 
What is struts_en
What is struts_enWhat is struts_en
What is struts_en
 
Spring Transaction
Spring TransactionSpring Transaction
Spring Transaction
 
PATTERNS07 - Data Representation in C#
PATTERNS07 - Data Representation in C#PATTERNS07 - Data Representation in C#
PATTERNS07 - Data Representation in C#
 
Best practices in using Salesforce Metadata API
Best practices in using Salesforce Metadata APIBest practices in using Salesforce Metadata API
Best practices in using Salesforce Metadata API
 
Dataware housing
Dataware housingDataware housing
Dataware housing
 
Sql storeprocedure
Sql storeprocedureSql storeprocedure
Sql storeprocedure
 
A Data Warehouse And Business Intelligence Application
A Data Warehouse And Business Intelligence ApplicationA Data Warehouse And Business Intelligence Application
A Data Warehouse And Business Intelligence Application
 
Focus
FocusFocus
Focus
 
SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015
 
Best practices in using Salesforce Metadata API
Best practices in using Salesforce Metadata APIBest practices in using Salesforce Metadata API
Best practices in using Salesforce Metadata API
 
Unit-IV-Introduction to Data Warehousing .pptx
Unit-IV-Introduction to Data Warehousing .pptxUnit-IV-Introduction to Data Warehousing .pptx
Unit-IV-Introduction to Data Warehousing .pptx
 
Data Models Breakout Session
Data Models Breakout SessionData Models Breakout Session
Data Models Breakout Session
 
Retail products - machine learning recommendation engine
Retail products   - machine learning recommendation engineRetail products   - machine learning recommendation engine
Retail products - machine learning recommendation engine
 
Cognos framework manager
Cognos framework managerCognos framework manager
Cognos framework manager
 
Murach : How to work with session state and cookies
Murach : How to work with session state and cookiesMurach : How to work with session state and cookies
Murach : How to work with session state and cookies
 
Z36149154
Z36149154Z36149154
Z36149154
 
Data Seeding via Parameterized API Requests
Data Seeding via Parameterized API RequestsData Seeding via Parameterized API Requests
Data Seeding via Parameterized API Requests
 

Recently uploaded

Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage examplePragyanshuParadkar1
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIkoyaldeepu123
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 

Recently uploaded (20)

Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage example
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AI
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 

Spring Data JPA in detail with spring boot

  • 2. Pagination and Sorting  Pagination is often helpful when we have a large dataset and we want to present it to the user in smaller chunks.  Also, we often need to sort that data by some criteria while paging.  While dealing with large amount of data the lazy processing is often essential. Even if a service returns a huge amount of data the consumer is less likely using it.  Consider a shopping website, where customer searches for a product and the website has thousands of products to display. Fetching thousands of products and displaying it on a web page will be very time consuming. In most of the cases the customer may not even look at all of the products.
  • 3. contd  For such cases a technique called as Pagination is used. Only a small subset of products (page) is displayed at first and customer can ask to see the next subset (page) and so on. This is called as Pagination.  Pagination allows the users to see a small portion of data at a time (a page), and sorting allows the users to view the data in a more organized way. Both paging and sorting help the users consume information more easily and conveniently.
  • 4. Query Approaches Spring Data by default provides the following query methods through its interface:  findAll //Returns all entities  findById(ID id) //Returns the entity depending upon given id  What if one wants to query customer records based on the customer's address?  How does Spring support this scenario?  Spring supports these kinds of scenarios using the following approaches:  Query creation based on the method name.  Query creation using @NamedQuery: JPA named queries through a naming convention.  Query creation using @Query: annotate the query method with @Query.
  • 5.  Query method names are derived by combining the property name of an entity with supported keywords such as "findBy", "getBy", "readBy" or "queryBy". findBy <DataMember><Op>
  • 6. Customer class public class Customer { private Long phoneNumber; private String name; private Integer age; private Character gender; private String address; private Integer planId; //getters and setters } To query a record based on the address using query creation by the method name, the following method has to be added to the CustomerRepository interface. interface CustomerRepository extends JpaRepository<Customer, Long> { Customer findByAddress(String address); // method declared }
  • 7. contd  If a query is provided using more than one approach in an application. What is the default precedence given by the Spring? Following is the order of default precedence:  @Query always takes high precedence over other options  @NameQuery  findBy methods
  • 8.  @Query Annotation is used for defining custom queries in Spring Data JPA. When you are unable to use the query methods to execute database operations then you can use @Query to write a more flexible query to fetch data.  @Query Annotation supports both JPQL and native SQL queries.
  • 9. JPQL JPQL is an object-oriented query language that is used to perform database operations on persistent entities. Instead of a database table, JPQL uses the entity object model to operate the SQL queries. Here, the role of JPA is to transform JPQL into SQL. Thus, it provides an easy platform for developers to handle SQL tasks. Features:  The features of JPQL are that it can:  perform join operations  update and delete data in a bulk  perform an aggregate function with sorting and grouping clauses  provide both single and multiple value result types
  • 10. JPQL  @Query("SELECT * FROM Student ORDER BY age") Optional<Student> findSortedStudentByAge();
  • 11. Native Query  If you want to use this native query in the Spring Boot project then we have to take the help of @Query Annotation and we have to set an attribute nativeQuery=true in Query annotation to mark the query as native. @Query(nativeQuery = true, value = "SELECT * FROM Student ORDER BY age") Optional<Student> findSortedStudentByAge();
  • 12. Creating Queries using JPQL: JPQL provides two methods that can be used to perform database operations. They are: - Query createQuery(String name) - The createQuery() method of EntityManager interface is used to create an instance of the Hibernate Query interface for executing JPQL statement. This method creates dynamic queries that can be defined within business logic.
  • 13.  Fetching all the Customer names: Query query = em.createQuery("Select c.name from CustomerEntity c");
  • 14. NamedQuery  Named queries are one of the core concepts in JPA. They enable you to declare a query in your persistence layer and reference it in your business code. That makes it easy to reuse an existing query. It also enables you to separate the definition of your query from your business code.  Named queries make it easier to maintain and reuse complex database queries by giving them a recognizable name. Instead of writing the entire query every time you need to use it, you can refer to it by its name. This improves code readability, maintainability, and reduces redundancy.
  • 15. NamedQuery Query createNamedQuery(String name) - The createNamedQuery() method of EntityManager interface is used to create an instance of the Hibernate Query interface for executing named queries. This method is used to create static queries that can be defined in the entity class. Ex: @NamedQuery(name = "getAll" , query = "Select c from CustomerEntity s")
  • 16.  In an enterprise application, a transaction is a sequence of actions performed by the application that together pipelined to perform a single operation. For example, booking a flight ticket is also a transaction where the end user has to enter his information and then make a payment to book the ticket.
  • 17. Why Do We Need Transaction Management?  Let’s understand transactions with the above example, if a user has entered his information the user’s information gets stored in the user_info table. Now, to book a ticket he does an online payment and due to some reason(system failure) the payment has been canceled so, the ticket is not booked for him. But, the problem is that his information gets stored on the user_info table. On a large scale, more than thousands of these things happen within a single day. So, it is not good practice to store a single action of the transaction
  • 18. contd  To overcome these problems, spring provides transaction management, which uses annotation to handle these issues. In such a scenario, spring stores the user information in temporary memory and then checks for payment information if the payment is successful then it will complete the transaction otherwise it will roll back the transaction and the user information does not gets stored in the database.
  • 19. EX:
  • 20. Programmatic vs. Declarative  Spring supports two types of transaction management −  Programmatic transaction management − This means that you have to manage the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain.  Declarative transaction management − This means you separate transaction management from the business code. You only use annotations or XML-based configuration to manage the transactions.
  • 21. contd  @Transactional annotation, which provides broad support for transaction management and allows developers to concentrate on business logic rather than worrying about data integrity in the event of system failures
  • 22.  Spring Data JPA already provides many solutions that allow us to query data easier such as Query Method, Query Method, or four repository  interface(JpaRepository, PagingAndSortingRepos itory, CrudRepository, Repository). These features are powerful, which help me a lot when building an application with Spring Data JPA. But a lot of time we still need to custom query or method to meet expectations or requirements.