YDP_API&MS_UNIT_III[1]
YDP_API&MS_UNIT_III[1]
UNIT III
SPRING DATA JPA WITH BOOT
Y DURGA PRASAD
Associate Professor
Department of Computer Science and Engineering
ADITYA
For implementing the Persistence Layer of an enterprise application Spring uses many approaches. A developer can
choose appropriate Spring modules such as Spring JDBC, Spring ORM, or Spring Data JPA for implementing the
data access layer of an enterprise application depending on the repository type. Spring simplifies transactions by
allowing the developer to implement transactions in a declarative way using simple annotations and configurations.
Three-tier application that consists of
❑Presentation Layer
❑Service/Business Layer
❑Persistence Layer
Let us understand the limitations of JDBC API
❑A developer needs to open and close the connection.
❑A developer has to create, prepare, and execute the statement and also maintain the
resultset.
❑A developer needs to specify the SQL statement(s), prepare, and execute the
statement.
❑A developer has to set up a loop for iterating through the result (if any).
❑A developer has to take care of exceptions and handle transactions.
The above limitations can be solved with the technologies Spring ORM. 2
ADITYA
❖Object Relational Mapping (ORM) is a technique or design pattern, which maps object models with the relational
model. It has the following features:
❑It resolves the object-relational impedance mismatch by mapping
✓Java classes to tables in the database
✓Instance variables to columns
✓Objects to rows in the table
❑It helps the developer to get rid of SQL queries. They can concentrate on the business logic and work with
the object model which leads to faster development of the application.
❑It is database independent. All database vendors provide support for ORM. Hence, the application
becomes portable without worrying about the underlying database.
❖Benefits of Object Relational Mapping(ORM)
❑ORM provides a programmatic approach to implement database operations.
❑ORM maps Java objects to the relational database tables in an easier way based on simple configuration.
❑Supports simple query approaches like HQL(Hibernate Query language) and JPQL (Java Persistence
Query Language)
❑Supports object-oriented concepts such as inheritance, mapping, etc.
❖To use ORM in Java applications Java Persistence API (JPA) specification is used. There are several
implementations of JPA available in the market, such as Hibernate, OpenJPA, DataNucleus, EclipseLink, etc.
EclipseLink is the reference implementation for JPA.
3
ADITYA
The Java Persistence API (JPA) is a Java EE specification that defines how data persistence‐related tasks are handled
using object‐relational mapping (ORM) frameworks in Java applications. It provides the following features:
➢Defines an API for mapping the object model with the relational model
➢Defines an API for performing CRUD operations
➢Standardizes ORM features and functionalities in Java.
➢Provides an object query language called Java Persistence Query Language (JPQL) for querying the database.
➢Provides Criteria API to fetch data over an object graph.
4
ADITYA
5
ADITYA
❑Limitations while using ORM
➢The Programmer has to write the code to perform common database operations(CRUD operations) in
repository class implementation.
➢A developer can define the required database access methods in the repository implementation class in
his/her own way, which leads to inconsistency in the data access layer implementation.
❑Spring Data is a high-level project from Spring whose objective is to unify and ease access to different types of
data access technologies including both SQL and NoSQL data stores.
❑Spring Data simplifies the data access layer by removing the repository(DAO) implementations entirely from
your application. Now, the only artifact that needs to be explicitly defined is the interface
❑Spring Data JPA helps to implement the persistence layer by reducing the effort that is actually needed.
❑Provides basic interfaces to support the following commonly used database operations:
✓Performing CRUD (create, read, update, delete) operations
✓Sorting of data
✓Pagination of data
✓Spring Data provides persistent technology-specific abstractions as interfaces through its sub-projects.
✓JpaRepository interface to support JPA.
✓MongoRepository interface to support MongoDB and many more.
6
ADITYA
7
ADITYA
❑The property spring.jpa.hibernate.ddl-auto is for database initialization. It is good security practice that after
your database is in production state, you make this none. property makes sure that the database tables and the
domain models in your application are in sync. Whenever you change the domain model, hibernate will
automatically update the mapped table in the database when you restart the application.Here are some
commonly used ddl values:
❑none: The default for MySQL. We make no change to the database structure.
❑update: Hibernate changes the database according to the entity structures.
❑create: Creates the database every time but does not drop it on close.
❑create-drop: Creates the database and drops it when SessionFactory closes.
❑spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect
The SQL dialect makes Hibernate generate better SQL for the chosen database
❑spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
to show the hibernate-generated SQL into the console
8
ADITYA
Query Approaches
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
9
ADITYA
10
ADITYA
Though a query created from the method name suits very well but, in certain situations, it is difficult to derive a
method name for the required query.
The following options can be used in these scenarios:
Using JPA NamedQueries: JPA named queries through a naming convention
Using @Query: Use @Query annotation to your query method
12
ADITYA
Spring Data allows @Query annotation provides a generic (JPQL) or a database-specific native (SQL) query.
JPQL
@Query("select n FROM CseQueryEntity n")
//public List<CseQueryEntity> getAll();
//@Query("select n FROM CseQueryEntity n WHERE n.course='devops'")
//public List<CseQueryEntity> getByCo();
13
ADITYA
14
ADITYA
Spring Transaction Management is one of the most widely used and important feature of Spring framework.
Transaction Management is a trivial task in any enterprise application. Spring provides extensive support for
transaction management and help developers to focus more on business logic rather than worrying about the
integrity of data incase of any system failures.
15
ADITYA
@Transactional annotation supports the following attributes:
❑Transaction isolation: The degree of isolation of this transaction with other transactions.
❑Transaction propagation: Defines the scope of the transaction.
❑Read-only status: A read-only transaction will not modify any data. Read-only transactions can be useful for
optimization in some cases.
❑Transaction timeout: How long a transaction can run before timing out.
16
ADITYA
❑Dirty read: SQL-transaction T1 modifies a row. SQL- transaction T2 then reads that row before T1 performs a
COMMIT. If T1 then performs a ROLLBACK, T2 will have read a row that was never committed and that may thus
be considered to have never existed.
❑Non-repeatable read: SQL-transaction T1 reads a row. SQL- transaction T2 then modifies or deletes that row and
performs a COMMIT. If T1 then attempts to reread the row, it may receive the modified value or discover that the
row has been deleted.
❑Phantom: SQL-transaction T1 reads the set of rows N that satisfy some . SQL-transaction T2 then executes SQL-
statements that generate one or more rows that satisfy the used by SQL-transaction T1. If SQL-transaction T1 then
repeats the initial read with the same , it obtains a different collection of rows.
17
ADITYA
Propagation in Spring transactions determines how transactions should behave when they are nested within other
transactions. Here are the available propagation options:
18
ADITYA
Read-only status
❑ The readOnly attribute specifies that the transaction will only read data from a database.
❑ A read-only transaction can be used when your code reads but does not modify data.
❑ The advantage is that the database may apply certain optimization to the transaction when it is declared to be
read-only.
Time Out
The transaction timeout has to be set within which the transaction must be completed for better application
performance.Spring supports the timeout attribute for transactions. A transaction timeout can be configured that
determines the maximum time (in seconds) within which a transaction has to commit, failing which the transaction
will be rolled back.
@Transactional default rollback behavior
Spring automatically rolls back the transaction for run time exception and proceeds to commit the transactions
for checked exceptions.
Overriding default rollback behavior: Use the rollbackFor and noRollbackFor attributes of @Transactional
annotation to override the default rollback behavior. 19
ADITYA
Update Operation in Spring Data JPA
❑ @Query annotation for query operations.
❑@Query annotation can execute modifying queries such as update, delete or insert operations using @Query
annotation along with @Transactional and @Modifying annotation at query method.
public interface CustomerRepository extends JpaRepository<Customer, Long> {
@Transactional
@Modifying(clearAutomatically = true)
@Query("update Customer c set c.name = ?1 where c.address = ?2")
void update(String name, String address);
}
@Modifying: This annotation will trigger @Query annotation to be used for an update operation instead of a
query operation.
@Modifying(clearAutomatically = true): After executing modifying query, EntityManager might contain
unrequired entities. It is a good practice to clear the EntityManager cache automatically by setting @Modifying
annotation’s clearAutomatically attribute to true.
@Transactional: Spring Data provided CRUD methods on repository instances that support transactional by default
with read operation and by setting readOnly flag to true. Here, @Query is used for an update operation, and
hence we need to override default readOnly behavior to read/write by explicitly annotating a method with
20
@Transactional.
ADITYA
21
ADITYA
22
ADITYA