0% found this document useful (0 votes)
5 views

YDP_API&MS_UNIT_III[1]

The document discusses the implementation of the Persistence Layer in enterprise applications using Spring Data JPA, highlighting the advantages of Object Relational Mapping (ORM) and the Java Persistence API (JPA). It outlines the features and limitations of ORM, the role of Spring Data in simplifying data access, and various query approaches available in Spring Data JPA. Additionally, it covers transaction management in Spring, best practices for using Spring Data JPA, and the differences between @Service, @Repository, and @Controller annotations.

Uploaded by

balajikukkapalli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

YDP_API&MS_UNIT_III[1]

The document discusses the implementation of the Persistence Layer in enterprise applications using Spring Data JPA, highlighting the advantages of Object Relational Mapping (ORM) and the Java Persistence API (JPA). It outlines the features and limitations of ORM, the role of Spring Data in simplifying data access, and various query approaches available in Spring Data JPA. Additionally, it covers transaction management in Spring, best practices for using Spring Data JPA, and the differences between @Service, @Repository, and @Controller annotations.

Uploaded by

balajikukkapalli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

API AND MICROSERVICES

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

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.

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

Single Entity based on the primary key.


➢findById(Long id);
➢readById(Long id);
➢getById(Long id);
➢queryById(Long id);

Query Methods to Retrieve Multiple Entities

➢findByAgeAndHeight(Integer age, Double height);


➢findByAgeAndNameAndColor(Integer age, String name, String color);
➢findByNameOrAge(String name, Integer age);
➢findByNameIgnoreCaseAndColor(String name, String color);

10
ADITYA

Query Methods to Count Entities


➢Integer countByName(String name);
➢Integer countByNameAndLastName(String name, String lastName);
Query Methods to Find the First N Entities
➢findFirstByName(String name);
➢findTopByName(String name);
➢findTop10ByColor(String color):specify the number of entities we want to retrieve.
Complex Queries with Query Method – Comparison Queries
➢findByNameContaining(String subName);
➢findByNameStartingWith(String subName);
➢findByHeightLessThan(double height);
➢findByAgeLessThanOrHeightGreaterThan(Integer age, double height);
➢findByAgeGreaterThanAndAgeLessThan(Integer ageStart, Integer ageEnd);
➢findByAgeGreaterThanEqual(Integer age);
➢findByDateOfBirthBetween(Date start, Date end); 11
ADITYA
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

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

database-specific native (SQL) query

//@Query("select n FROM CseQueryEntity n WHERE n.course='devops'")


//public List<CseQueryEntity> getByCo();
//@Query(value="select * from cse_query where course='devops'",
//nativeQuery=true)
//public List<CseQueryEntity> getByCo();

13
ADITYA

Spring Data JPA Named Query


The declaration of named query over entity classes is same in spring data JPA as in plain JPA. Only the difference is
how these named quires are called to execute the data base query.
If the JPQL query strings are used many number of times then that query can be declared as a template. To declare
query templates statically use the NamedQuery and NamedQueries annotations.
NamedQuery and NamedQueries annotations can be declared over entity class. NamedQuery annotation declares
a single named query. This takes two arguments one is the name for the query and second is the JPQL query string.

@NamedQuery(name="CseQueryEntity.getData",query="FROM CseQueryEntity n WHERE n.course='api'")


@NamedNativeQuery(name="CseQueryEntity.getData",query="SELECT * FROM cse_query where
pin=503",resultClass=CseQueryEntity.class)

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

What’s the difference between @Service, @Repository, and @Controller in Spring?


These are all stereotype annotations that mark classes as Spring components. They each serve different roles within
the MVC pattern:
@Repository classes interact with the database and handle data operations,
@Service classes contain business logic
@Controller classes handle incoming HTTP requests and return responses.

Best Practices: SPRING DATA JPA

1. Let Spring Framework do the transaction management


2. Use @Transactional annotation at Service layer
3. Know the defaults of the @Transactional annotation
4. Take care of the method call while using the @Transactional

21
ADITYA

Best Practices:SPRING APPLICATION


1. Use Spring Initializr for creating Spring Boot projects
2. Use the correct project Structure while creating Spring Boot projects
3. Choose Java-based configuration over XML based configuration
4. Use Setter injection for optional dependencies and Constructor injection for mandatory dependencies
5. Use @Service for Business Layer classes
6. Follow the Spring bean naming conventions while creating beans

Best Practices - Spring Data JPA

1. Extended interface usage


2. Don't fetch more data than you need
3. @NamedQuery vs @Query
4. JPQL in Custom Repository

22
ADITYA

You might also like