0% found this document useful (0 votes)
41 views19 pages

Unit - 3-2

Uploaded by

sreeranganadh008
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)
41 views19 pages

Unit - 3-2

Uploaded by

sreeranganadh008
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/ 19

What is API

API (Application programming interface) is a document that contains features of a


product or software. It represents classes and interfaces that software programs can
follow to communicate with each other. An API can be created for applications,
libraries, operating systems, etc.

Java JDBC
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute
the query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API
uses JDBC drivers to connect with the database. There are four types of JDBC drivers:

o JDBC-ODBC Bridge Driver,


o Native Driver,
o Network Protocol Driver, and
o Thin Driver

We can use JDBC API to access tabular data stored in any relational database. By the
help of JDBC API, we can save, update, delete and fetch data from the database. It is
like Open Database Connectivity (ODBC) provided by Microsoft.

Why Should We Use JDBC


Before JDBC, ODBC API was the database API to connect and execute the query with
the database. But, ODBC API uses ODBC driver which is written in C language (i.e.
platform dependent and unsecured). That is why Java has defined its own API (JDBC
API) that uses JDBC drivers (written in Java language).

We can use JDBC API to handle database using Java program and can perform the
following activities:

1. Connect to the database


2. Execute queries and update statements to the database
3. Retrieve the result received from the database.

What are the advantages and limitations of JDBC Prepared Statement?


Following are the advantages of the prepared statement:
• By avoiding multiple compilation and execution of statements, prepared
statements perform faster.
• Using prepared statements, we can insert values to advanced datatypes such
as BLOB, CLOB, OBJECT easily with the help of the setter methods provided
by the Prepared Statement interface.
• By providing setter method to set values prepared statement avoids the use of
quotes and other special characters with in the query, and thereby it escapes
the SQL injection attacks.

Following are the limitations of prepared statements:


• Since a PreparedStatement object represents only one SQL statement at a
time, we can execute only one statement by one prepared statement object.
• To prevent injection attacks it does not allow more than one value to a place
holder.
• if we want to change database s/w in the middle of project development it is not
possible,we have to re develop JDBC persistence logic for other database s/w's.
• By default JDBC ResultSet object is not serializable, so we can not send that
object over the network.To overcome this RowSet introduced but that is not
supporting for all JDBC drivers.

Spring Data JPA?

JPA is a Java specification (Java Persistence API) and it manages


relational data in Java applications . To access and persist data
between Java object(Plain Old Java object)/ class and relational database, we
can use JPA. Upon Object-Relation Mapping (ORM), it follows the
mechanisms. It has the runtime EntityManager API (table is called entity)
and JPA is responsible for processing queries and transactions on the
Java objects against the database. The main highlight is it uses JPQL (Java

Persistent Query Language) which is platform-independent.

JPA mainly covers persistence in terms of


• The Java Persistence API
• Object-Relational metadata
• Moreover under the persistence package API is defined.
• We cannot say that JPA is a framework, but It defines a concept and it can
be implemented by any framework.
Advantages of Using JPA
• No need to write DDL/DML queries, instead we can map by using
XML/annotations.
• JPQL is used and since it is platform-independent, we no need to depend
on any native SQL table. Complex expressions and filtering( where clause
in query) expressions are all handled via JPQL only.
• Entity can be partially stored in one database like MySQL and the rest can
be in Graph database Management System.
• Dynamic generation of queries is possible.
• Integration with Spring framework is easier with a custom namespace.
Units comprised in JPA are available under javax persistence package:
It has static methods to obtain an EntityManagerFactory
Persistence instance

Factory class for EntityManager and responsible for


EntityManagerFactory managing multiple instances of EntityManager

EntityManager It is an interface that works for the Query instance

They are persistent objects and stored as records in the


Entity database

Persistence Unit Set of all entity classes

EntityTransaction It has one-to-one relationship with EntityManager.

Query To get relation objects that meet the criteria.


To leveraging the Spring Data programming model with JPA, a DAO
interface needs to extend the JPA
specific Repository interface, JpaRepository. This will enable Spring Data to
find this interface and automatically create an implementation for it.
By extending the interface, we get the most relevant CRUD methods for
standard data access available in a standard DAO.

Custom Access Method and Queries


To define more specific access methods, Spring JPA supports quite a few
options:

• simply define a new method in the interface


• provide the actual JPQL query by using the @Query annotation
• use the more advanced Specification and Querydsl support in
Spring Data
• define custom queries via JPA Named Queries

The third option, Specifications and Querydsl support, is similar to JPA


Criteria, but uses a more flexible and convenient API. This makes the
whole operation much more readable and reusable. The advantages of this
API will become more pronounced when dealing with a large number of
fixed queries, as we could potentially express these more concisely through
a smaller number of reusable blocks.
The last option has the disadvantage that it either involves XML or
burdening the domain class with the queries.

Automatic Custom Queries


When Spring Data creates a new Repository implementation, it analyses all
the methods defined by the interfaces and tries to automatically generate
queries from the method names. While this has some limitations, it's a
very powerful and elegant way of defining new custom access methods
with very little effort.
Let's look at an example. If the entity has a name field (and the Java Bean
standard getName and setName methods), we'll define
the findByName method in the DAO interface. This will automatically
generate the correct query:’
public interface IFooDAO extends JpaRepository<Foo, Long> { Foo
findByName(String name); }

Manual Custom Queries


Now let's look at a custom query that we'll define via
the @Query annotation:
@Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)")
Foo retrieveByName(@Param("name") String name);Copy
For even more fine-grained control over the creation of queries, such as
using named parameters or modifying existing queries, the reference is a
good place to start.

Spring Boot Starter Data JPA dependency that will automatically


configure the DataSource for us.
We need to make sure that the database we want to use is present in the
classpath. In our example, we've added the H2 in-memory database:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-
jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
</dependency>

Spring Boot – Spring Data JPA


Spring Data JPA or JPA stands for Java Persistence API, so before looking
into that, we must know about ORM (Object Relation Mapping). So Object
relation mapping is simply the process of persisting any java object directly
into a database table. Usually, the name of the object being persisted becomes
the name of the table, and each field within that object becomes a column.
With the table setup set up, each row corresponds to a record in the
application. Hibernate is one example of ORM. In short, JPA is the interface
while hibernate is the implem entation.

The java persistence API provides a specification for


persisting, reading, and managing data from your java object to your

relational tables in the database. JPA is just guidelines to implement

ORM and there is no underlying code for the implementation. Spring Data JPA
is part of the spring framework. The goal of spring data repository abstraction
is to significantly reduce the amount of boilerplate code required to implement
a data access layer for various persistence stores. Spring Data JPA is not a
JPA provider, it is a library/framework that adds an extra layer of abstraction
on the top of our JPA provider line Hibernate.

Object-Relation Mapping (ORM)


In ORM, the mapping of Java objects to database tables, and vice-versa is
called Object-Relational Mapping. The ORM mapping works as a bridge between

a relational database (tables and records) and Java application (classes and objects).

In the following figure, the ORM layer is an adapter layer. It adapts the language of
object graphs to the language of SQL and relation tables.
The ORM layer exists between the application and the database. It converts the Java classes
and objects so that they can be stored and managed in a relational database. By default, the
name that persists become the name of the table, and fields become columns. Once an
application sets-up, each table row corresponds to an object.

https://www.javatpoint.com/spring-boot-jpa
https://www.geeksforgeeks.org/spring-boot-spring-data-jpa/

Configuring Spring Data JPA with Spring Boot


The easiest way to configure Spring Data JPA with spring boot is to
use the Spring Initializr to set up your build process and add all
required dependencies.
For all existing Spring Boot projects, you need to add the spring-
boot-starter-data-jpa module.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-
jpa</artifactId>
</dependency>
You also need to add a dependency to a database-specific JDBC
driver. I will connect to a PostgreSQL database and, therefore, need
a dependency on PostgreSQL’s JDBC driver.
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>${postgresql.version}</version>
</dependency>

Default Configuration
• a dependency on the HikariCP(Mysql) connection pool and a
basic default configuration. You can set all of HikariCP’s
configuration parameters in your application.properties file by
adding the prefix spring.datasource.hikari to the parameter
name.
• Most enterprise applications use a standalone database, e.g.,
a PostgreSQL or Oracle database server. In that case, you only
need to provide the URL, user name, and password to connect
to that database. You can do that by setting the following 3
configuration properties in your application.properties file.

• spring.datasource.url=jdbc:postgresql:
//localhost:5432/test
• spring.datasource.username=postgres
• spring.datasource.password=postgres

Customizing the Default Configuration


You can easily change the default behaviour and integration by
providing different dependencies and adding a few parameters to
your configuration.

Spring Boot adds a dependency to HikariCP ( A solid High-


Performance JDBC connection) ) and configures it. You can use a
different connection pool by excluding HikariCP from your project
dependencies.
<dependency>
<groupId>org.springframework.boot</gr
oupId>
<artifactId>spring-boot-starter-data-
jpa</artifactId>
<exclusions>
<exclusion>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifac
tId>
</exclusion>
</exclusions>
</dependency>
Spring Boot then tries to find the following connection pooling
implementations in the described order on the classpath and uses
the first one it finds:

• Tomcat Connection Pooling,


• Commons DBCP2,
• Oracle UCP.

If you don’t want to rely on a scan of your application classpath, you


can also specify the connection pool explicitly by configuring
the spring.datasource.type property.
spring.datasource.type=org.apache.tomcat.jdbc.pool.Dat
aSource
After you changed the connection pool, you can set all of its standard
configuration parameters in the application.properties file by
adding the
prefix spring.datasource.tomcat, spring.datasource.dbcp2,
or spring.datasource.oracleucp to the parameter name.

Deactivating Spring Data JPA’s Repositories


I recommend using Spring Data JPA’s repositories. They make the
implementation of your persistence much easier by providing a set of
standard methods to persist, read and delete entities.
If you decide not to use these features, you can deactivate all JPA
repositories in your configuration.

spring.data.jpa.repositories.enabled=false

Development Configuration
To enable you to understand how your application interacts with
the database and find performance issues before deploying them to
production.

To get all the required information, I recommend using the


following configuration.

logging.level.org.hibernate=INFO
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.cache=DEBUG
logging.level.org.hibernate.stat=DEBUG

This activates Hibernate’s statistics component. It provides you a


summary of the number and the time Hibernate spent executing the
most important operations during each session. It also adds all
executed SQL statements to the log file and shows you how Hibernate
used the 2nd level cache.

Production Configuration
In production, you should set Hibernate’s log level to ERROR to
keep the overhead as small as possible.

logging.level.org.hibernate=ERROR

Configuring JPA and Hibernate Properties


When you’re using JPA and Hibernate without Spring Data
JPA, you usually configure it using a persistence.xml file. Within
the properties element of that XML file, you can provide vendor-
specific configuration parameters.
You can set all of these parameters in your application.properties file
by adding the prefix spring.jpa.properties to the configuration
property’s name.
spring.jpa.properties.hibernate.generate_statistics=true

Configuring Database Creation


By default, Spring Boot automatically creates in-memory databases
for you. This is deactivated for all other databases. You can activate
it by setting the property spring.jpa.hibernate.ddl-
auto to none, validate, update, or create-drop.
spring.jpa.hibernate.ddl-auto=create-drop
Conclusion
Spring Boot’s starter for Spring Data JPA adds the most common
dependencies and a reasonable default configuration to your
application. The only thing you need to add is the connection
information for your database.

Pagination and Sorting using Spring Data JPA


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.

Initial Setup
First, let’s say we have a Product entity as our domain class
@Entity
public class Product {
@Id
private long id;
private String name;
private double price;
// constructors, getters and setters
}
Each of our Product instances has a unique identifier: id, its name and
its price associated with it.
To access our Products, we’ll need a ProductRepository:
public interface ProductRepository extends
PagingAndSortingRepository<Product, Integer> {
List<Product> findAllByPrice(double price, Pageable
pageable);
}
By having it extend PagingAndSortingRepository, we
get findAll(Pageable pageable) and findAll(Sort sort) methods for
paging and sorting.
Conversely, we could have chosen to extend JpaRepository instead, as it
extends PagingAndSortingRepository too.
Once we extend PagingAndSortingRepository, we can add our own
methods that take Pageable and Sort as parameters, like we did here
with findAllByPrice.
Let’s take a look at how to paginate our Products using our new method.

Pagination
Once we have our repository extending from PagingAndSortingRepository,
we just need to:

1. Create or obtain a PageRequest object, which is an implementation


of the Pageable interface
2. Pass the PageRequest object as an argument to the repository
method we intend to use

We can create a PageRequest object by passing in the requested page


number and the page size.
Here the page count starts at zero:
Pageable firstPageWithTwoElements =
PageRequest.of(0, 2);
Pageable secondPageWithFiveElements =
PageRequest.of(1, 5);
In Spring MVC, we can also choose to obtain the Pageable instance in our
controller using Spring Data Web Support.
Once we have our PageRequest object, we can pass it in while invoking
our repository’s method:
Page<Product> allProducts =
productRepository.findAll(firstPageWithTwoElements);
List<Product> allTenDollarProducts =
productRepository.findAllByPrice(10,
secondPageWithFiveElements);
The findAll(Pageable pageable) method by default returns
a Page<T> object.
However, we can choose to return either a Page<T>, a Slice<T>, or
a List<T> from any of our custom methods returning paginated data.
A Page<T> instance, in addition to having the list of Products, also knows
about the total number of available pages. It triggers an additional count
query to achieve it. To avoid such an overhead cost, we can instead
return a Slice<T> or a List<T>.
A Slice only knows whether the next slice is available or not.

Pagination and Sorting


Similarly, to just have our query results sorted, we can simply pass an
instance of Sort to the method:
Page<Product> allProductsSortedByName =
productRepository.findAll(Sort.by("name"));Copy
However, what if we want to both sort and page our data?
We can do that by passing the sorting details into our PageRequest object
itself:
Pageable sortedByName = PageRequest.of(0, 3,
Sort.by("name"));
Pageable sortedByPriceDesc = PageRequest.of(0,
3, Sort.by("price").descending());
Pageable sortedByPriceDescNameAsc =
PageRequest.of(0,5,
sort.by("price").descending().and(Sort.by("na
me")));
Based on our sorting requirements, we can specify the sort fields and the
sort direction while creating our PageRequest instance.
Spring Boot Query Approaches

Spring Boot JPA - Named Queries


We need a custom query to fulfil one test case. We can use @NamedQuery
annotation to specify a named query within an entity class and then declare that
method in repository. Following is an example.

Entity - Entity.java

Following is the default code of Employee. It represents a Employee


table with id, name, age and email columns.

package com.tutorialspoint.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

@Entity
@Table
@NamedQuery(name = "Employee.findByEmail",
query = "select e from Employee e where e.email = ?1")
public class Employee {
@Id
@Column
private int id;

@Column
private String name;

@Column
private int age;

@Column
private String email;

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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}

Add a method to find an employee by its name and age.

package com.tutorialspoint.repository;

import
org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.tutorialspoint.entity.Employee;

@Repository
public interface EmployeeRepository extends
CrudRepository<Employee, Integer> {
public List<Employee> findByName(String name);
public List<Employee> findByAge(int age);
public Employee findByEmail(String email);
}

Now Spring JPA will create the implementation of above methods


automatically using the query provided in named query.

Spring Declarative Transaction Management


Declarative transaction management approach allows you to
manage the transaction with the help of configuration instead of
hard coding in your source code.

Programmatic Transaction Management

1. Allows us to manage transactions through programming in our source code.


2. This means hardcoding transaction logic between our business logic.
3. We use programming to manage transactions
4. Flexible, but difficult to maintain with large amount of business logic. Introduces boilerplate
between business logic.
5. Preferred when relative less transaction logic is to be introduced.
Declarative Transaction Management

1. Allows us to manage transactions through configuration.


2. This means separating transaction logic with business logic.
3. We use annotations (Or XML files) to manage transactions.
4. Easy to maintain. Boilerplate is kept away from business logic.
5. Preferred when working with large amount of Transaction logic.

• We use <tx:advice /> tag, which creates a transaction-


handling advice and at the same time we define a pointcut
that matches all methods we wish to make transaction and
reference the transactional advice.
• If a method name has been included in the transactional
configuration, then the created advice will begin the
transaction before calling the method.
• Target method will be executed in a try / catch block.
• If the method finishes normally, the AOP advice commits the
transaction successfully otherwise it performs a rollback.

Let us take a Student table, which can be created in MySQL TEST


database with the following DDL −

CREATE TABLE Student(


ID INT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(20) NOT NULL,
AGE INT NOT NULL,
PRIMARY KEY (ID)
);

Second table is Marks in which we will maintain marks for the


students based on years. Here SID is the foreign key for the
Student table.
CREATE TABLE Marks(
SID INT NOT NULL,
MARKS INT NOT NULL,
YEAR INT NOT NULL
);

Following is the content of the Data Access Object interface


file StudentDAO.java

package com.tutorialspoint;

import java.util.List;
import javax.sql.DataSource;

public interface StudentDAO {


/**
* This is the method to be used to initialize
* database resources ie. connection.
*/
public void setDataSource(DataSource ds);

/**
* This is the method to be used to create
* a record in the Student and Marks tables.
*/
public void create(String name, Integer age, Integer
marks, Integer year);

/**
* This is the method to be used to list down
* all the records from the Student and Marks
tables.
*/
public List<StudentMarks> listStudents();
}

Following is the content of the StudentMarks.java file

package com.tutorialspoint;

public class StudentMarks {


private Integer age;
private String name;
private Integer id;
private Integer marks;
private Integer year;
private Integer sid;

public void setAge(Integer age) {


this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setMarks(Integer marks) {
this.marks = marks;
}
public Integer getMarks() {
return marks;
}
public void setYear(Integer year) {
this.year = year;
}
public Integer getYear() {
return year;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public Integer getSid() {
return sid;
}
}
<beanid="dataSource"
class =
"org.springframework.jdbc.datasource.DriverManagerDataS
ource">
<property name = "driverClassName" value =
"com.mysql.jdbc.Driver"/>
<property name = "url" value =
"jdbc:mysql://localhost:3306/TEST"/>
<property name = "username" value = "root"/>
<property name = "password" value = "cohondob"/>
</bean>

id = "txAdvice" transaction-manager =
<tx:advice
"transactionManager">
<tx:attributes>
<tx:method name = "create"/>
</tx:attributes>
</tx:advice>

https://climbtheladder.com/10-spring-data-jpa-best-
practices/

https://medium.com/@eidan.khan659/how-to-optimize-
performance-with-spring-data-jpa-c615db786f7

You might also like