Spring Data JPA Notes
Spring Data JPA Notes
1) Java JDBC
2) Spring JDBC
3) Hibernate Framework
4) Spring ORM
5) Spring Data JPA
..
..
Note: If we have 5000 DB tables then we have to create 5000 DAO classes. Every dao
class should contain 4 common methods so it will become 20,000 methods with same
logic. (This is not recommended).
=> To avoid boiler plate code in DAO classes we can use Spring Data JPA.
=============================
Spring Data JPA Repositories
=============================
==========================================
Developing First Data JPA Application
========================================
1) Create Spring Boot application with dependencies
a) data-jpa-starter
b) mysql-driver
c) project-lombok
------------------------------------
@Data
@Entity
public class Book {
@Id
private Integer bookId;
private String bookName;
private Double bookPrice;
}
-----------------------------------------------------------------------
public interface BookRepository extends CrudRepository<Book, Integer>{
}
-----------------------------------------------------------------------
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/sbms
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
------------------------------------------------------
@SpringBootApplication
public class Application {
/*
* Book b = new Book(); b.setBookId(101); b.setBookName("Spring");
* b.setBookPrice(1000.00);
*
* repo.save(b);
*
* System.out.println("Record inserted.....");
*/
Optional<Book> findById = repo.findById(101);
System.out.println(findById.get());
}
}
======================
CrudRepository Methods
=======================
------------------------------------------------------------------
1) findBy Methods
2) Custom Queries
=================
Find By Methods
=================
-> Using Non Primary Key columns also we can select records
-> In findBy Methods method name is very important because based on method name JPA
will construct the query for execution.
===============
Custom Queries
===============
-> If we want to execute our query in JPA Repo then we can go for Custom Queries
1) HQL Queries
2) Native SQL queries
----------------------------------------------------------------------------
public interface BookRepository extends CrudRepository<Book, Integer> {
@Query("from Book")
public List<Book> getBooks();
=====================
HQL Vs SQL Queries
======================
#1
-> HQL queries are DB independent queries
-> SQL queries are DB dependent queries
#2
-> IN HQL query, we will use entity class name & variables
-> IN SQL query, we will use table name & column names
#3
-> HQL query can't execute in DB directley (conversion required)
-> SQL query can execute in DB directley
#4
-> Performance wise SQL queries are better
-> Maintanence wise HQL queries are better
Note: Every HQL query should be converted to SQL query before execution. That
conversion will done by Dialect class.
-> Every Database will have its own Dialect class.
Ex:
OracleDialect
MySqlDialect
DB2Dialect
PostgresDialect etc...
SQL : select * from book where book_price >= 2000 and book_name='Spring'
HQL : From Book where bookPrice >= 200 and bookName = 'Spring'
===============
JpaRepository
===============
System.out.println("record saved...");
--------------------------------------
findAll ( ) ;
findAll(Sort sort) ;
findAll (Pagebale pageable) ;
===========
Pagination
===========
Total records : 7
Page_Size : 3
@SpringBootApplication
public class Application {
EmployeeRepository repository =
context.getBean(EmployeeRepository.class);
int pageNo = 3;
PageRequest page = PageRequest.of(pageNo-1, 3);
emps.forEach(System.out::println);
}
}
===================
Query By Example
===================
-> It is used to prepare Dynamic Query based on data available in Entity class obj
@SpringBootApplication
public class Application {
emps.forEach(System.out::println);
}
}
===========
Assignment
===========
=====================
TimeStamping In JPA
=====================
-> It is used to insert CREATED_DATE & UPDATED_DATE columns values for the record
@Entity
@Table(name = "emp_tbl")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
@Id
private Integer empId;
private String empName;
private Double empSalary;
private String empGender;
private String dept;
@CreationTimestamp
@Column(name="date_created", updatable = false)
private LocalDate dateCreated;
@UpdateTimestamp
@Column(name="last_updated", insertable = false)
private LocalDate lastUpdated;
}
============
Generators
============
-> Generators are used to generate the value for Primary key Columns
1) UNIQUE
2) NOT NULL
1) AUTO
2) IDENTITY (mysql)
3) SEQUENCE (oracle)
4) TABLE : It will maintain another table to get primary key column values
===================
Custom Generator
===================
=> We want to generate primary key columns values as per project requirement like
below.
ORDER_DTLS table
-----------------
OD_1
OD_2
OD_3
...
OD_100
-> To achieve this requirement we need to develop our own generator. That is called
as Custom Generator.
String pk = prefix+suffix;
=========================================================================
----------------------------------------------------------------------------
=======================
Composite Primary Keys
=======================
=> Below is sql query to create a table with multiple primary key columns
Note: The class which is representing Composite Keys should implement Serializable
interface.
--------------------------------------------------------------------------
@Data
@Embeddable
public class AccountPK implements Serializable{
}
-------------------------------------------------------------------------
@Data
@Entity
@Table(name="account_tbl")
public class Account {
@EmbeddedId
private AccountPK accountPk;
}
--------------------------------------------------------------------------
public interface AccountRepo
extends JpaRepository<Account, AccountPK>{
}
----------------------------------------------------------------------------
@SpringBootApplication
public class Application {
/*
System.out.println("Record saved.....");
*/
}
============================================================================
=========================
Profiles in Spring Boot
=========================
-> Environments are used to test our application before delivering to client
3) UAT Env : Client / Client Side Team will use it for acceptance testing
5) PROD Env : Live Environment (endusers will access our prod app)
=> Every Environment will have its own Database and every database will have
seperate configuration properties (uname, pwd and URL)
=> If we want to deploy our code into multiple envrionments then we have to change
configuration properties in application.properties file for every deployment. (It
is not recommended).
1) DB Props
2) SMTP PRops
3) Kafka Props
4) Redis Props
application-dev.properties
application-sit.properties
application-uat.properties
application-pilot.properties
application-prod.properties
Note: Above represents application should load properties from Dev properties file.