Spring Boot Data Jpa
Spring Boot Data Jpa
JDBC+SQL
2. Java App <==============> RDBMS DB s/w
ORM
3. Java App <==============> RDBMS DB s/w
=====
JDBC
=====
- The JDBC API allows programmers and Java applications to interact with
databases.
- JDBC is a specification used for developing database applications with java
programming.
- JDBC provides interfaces like Connection, Statement, ResultSet...etc. and
those interfaces are implemented by database vendors like MySQL, Oracle…
etc.
- JDBC is Database independent API. If we want to move one db to another
db, Java code is same. Properties needs to be modified (driver class, url,
user, password) Some SQL Queries need to be modified.
JDBC Limitations:
- JDBC codes need SQL queries to develop persistence logic, 30% to 40% SQL
queries are DB dependent. So JDBC is DB dependent persistence logic.
- Boiler plate code problem (loading driver class, JDBC connection, create
statement, closing JDBC objects, exception handling… etc. repeat in multiple
part of the project.
- SQL Query need to be given by programmer.
- Schema creation, modification must be done by programmer.
Ex: table creation, alter table…
Chapter-02
Spring Boot Data JPA
- For all problem its throws only SQL exception with different messages i.e.
programmer cannot identify the problem clearly.
- SQLException are Checked Exception so, programmer will force to handle
exception which may create exception propagation issues.
==========================================================
In Spring Framework, before arrival of Spring Data to the market
==========================================================
Spring JDBC
- Spring Framework Provide Spring JDBC for SQL DB software based on Plain
JDBC.
- Spring JDBC module provides the abstraction on plain JDBC code by avoid
boiler plate code (Taking cares of common logic internally). Instead of
writing Plain JDBC code prefer to writing Spring JDBC code.
Spring ORM
- Spring framework provide Object based persistence logic Module Spring ORM.
Chapter-02
Spring Boot Data JPA
- Plain ORM framework (Hibernate) code contains lots of common logics. So, Spring
ORM avoid boiler plate code and provide abstraction on ORM and simplify ORM
persistence logic development with the support of HibernateTemplate classes.
Note: Before Spring Data there is no module in Spring framework to interact with NoSQL
based DB software. And to interact with SQL DB, Spring provide a separate module
(Spring JDBC), for ORM a separate module (Spring ORM) is given. That is no uniformity
and unified model for interacting with SQL and NoSQL DB Software.
Spring Data module is given Uniformity and unified model to interact both SQL DB
software (JDBC, ORM style) and NoSQL DB software.
Spring Data is the main Module of Spring Framework. Spring Data having 30+ sub
module like-
1. Spring Data JDBC
2. Spring Data JPA
3. Spring Data MongoDB
4. Spring Data Cassandra
5. ….
6. … etc.
Spring Data JDBC and JPA with Hibernate – No logics only create our own interface that
extends Spring data predefine Repository like CrudRepository,
PagingAndSortingRepository… etc. that provides readymade methods.
===============================
JPA-hibernate configs properties
Chapter-02
Spring Boot Data JPA
===============================
1. spring.jpa.database-platform= org.hibernate.dialect.OracleDialect
define dialect
For Oracle – OracleDialect means for all version
- OracleVersionDialect means for specific dialect.
It is optional property
Dialect: Dialect is the component which is internally used by hibernate to generate SQL
queries based on database and Vesion. Dialect will change version to version and DB to
DB.
2. spring.jpa.properties.format_sql = true
Show SQL queries as SQL format
3. Spring.jpa.show-sql=true
Hibernate internally generate SQL queries using the specified SQL dialect.
To see those generated queries as log message we need to use this above
property.
4. spring.jpa.hibernate.ddl.auto=update/ create/ create-drop/ validate
create: always create new DB table. If the DB table is already present then
it deletes the DB table and create new DB Table.
create-drop: create new table when application start and when we stop
application delete table. Use case in testing environment, UAT
environment.
validate: check DB is already available according to Entity class or not if not
then exception will raised.
update: Create new table if not exist, else use same table if table is
available according to Entity class. If entity class is modified then this
modification will affect to the DB table.
==================================
Basic JPA annotation for O-R mapping
Chapter-02
Spring Boot Data JPA
==================================
1. @Entity (mandatory): Maps java class with table and variables with columns.
2. @Id (mandatory): Indicates Primary Key column
3. @Table (Optional): If we did not specify then class name is taken as table name.
4. @Column (Optional): If we did not specify then variable name is taken as column
name.
5. @GeneratedValue: It is used to generate Primary Key value only on save.
6. @GeneratedValue (strategy=GenerationType.TypeName)
IDENTITY for MYSQL
SEQUENCE for ORACLE
AUTO for default BASED which DB we used.
7. @SequenceGenerator(name= “gen1”, initialValue=1000, allocationaSize=1
sequenceName = “empId_SEQ”)
======================
CrudRespository<T, ID>
======================
===============================
CrudRespository<T, ID> Methods
===============================
1. E save(E e)
This method takes one entity object and internally generate (JDBC+SQL) query to
insert this object as a record into a DB and return same object with generated PK
ID.
First it will check this entity already present inside DB table or not based on ID
“SELECT * FROM TABLE WHERE PK_COL = VAL”
If record is not present then internally execute hibernate persist() method that is
used to insert a new record.
Else record is already present then execute hibernate merge() method that is
used for update operation.
Example:
Employee emp = repo.save(employee);
emp.getEmpName();
emp.getEmpId();
2. saveAll (Iterable<s> entities);
Chapter-02
Spring Boot Data JPA
This method takes multiple objects at a time as a Collection type(List,
Set…) and performs same operation like save() method.
Examples:
1. Product p1 = new Product(10,"P2",300.0);
2. Product p2 = new Product(11,"P3",400.0);
3. Product p3 = new Product(12,"P4",500.0);
4.
5. List<Product> list = new ArrayList();
6. list.add(p1);
7. list.add(p2);
8. list.add(p3);
9. Iterable<Product> product = repo.saveAll(list);
(or)
1. Iterable<Product> product = repo.saveAll(Arrays.asList(p1,p2,p3));
3. long count()
This method returns total no. of rows/records present in DB table.
Example:
long noOfProduct = productRepo.count();
4. boolean existsById(id)
Chapter-02
Spring Boot Data JPA
It will check a particular record/row present in Db table or not based on
give id. If present then true, else false.
Example:
Boolean isProductAvailable = repo.existsById(11);
5. Iterable<T> findAll()
Get all records from DB table by generating and executing select query
without applying any conditions.
Internal SQL Query: select * from product;
Example:
1. Iterable<Product> data = repo.findAll();
2. //JDK 1.5 forEach Loop
3. for(Product pob:data) {
4. System.out.println(pob);
5. }
(Or)
Using “orElseThrow()” method:
1. Product p = repo.findById(11)
2. .orElseThrow(() -> new ProductNotFoundException("NOT EXIST"));
This line, if record is found the return entity object otherwise throw our customized
PNFE.
This line, if record is available returns entity object data otherwise return empty Product
object.
Option-02:
1. public String removeProductById(Integer pid){
2. Optional<Product> product = repo.findById(pid);
3. if(product.isPresent()){
4. repo.delete(product);
5. return “Product Deleted”;
6. }else{
7. return “Product not found”
8. }
9.}
Option-03
1. repo.delete(repo.findById(77)
2. .orElseThrow(()->new ProductNFException(“Product not found”)));
Option-04
1. Public String removeProduct(Product product){
2. repo.delete(product);
3. Return “Product deleted”;
4. }
9. void deleteById(ID)
Chapter-02
Spring Boot Data JPA
This method is used to delete one record based on ID given. It internally calls
delete method. First check object is present or not using findById if present call
delete(obj) method else throw exception like: EmptyResultDataAccessException.
Example:
(Or)
1. Iterable<Employee> sortEmp =repo.findAll(Sort.by(“empId”).ascending())
2. .forEach(System.out::println();
Chapter-02
Spring Boot Data JPA
2. by(Direction, String... properties) // var – arg method
Pass direction which order we want to sort and based on how many columns we
want.
Direction is Enum having two value ASC and DESC.
Example:
1. Sort s = Sort.by(Direction.DESC,"empId");
2. repo.findAll(s).forEach(System.out::println);
(Or)
1. Iterable<Employee> sortEmp
2. = repo.findAll(Sort.by(Direction.ASC, “empId”, “empJoinDate”);
3. for(Employee emp:sortEmp){
4. System.out.println(emp);
5. }
3. by(Order...)
This method is a var-arg method, used for mixing sorting order like one column
sort based on ascending order and one column based on descending order.
SQL query: select * from employee order by esal desc, dept asc;
Order is static inner class present inside Sort class and having static methods like-
<Order> asc(columnName)
<Order> desc(columnName)
<Order> by(columnName) // default sorting
Example:
1. Sort sort = Sort.by(Order.asc("empDept"),Order.desc("empSalary"))
2. repo.findAll(sort).forEach(System.out::println);
(Or)
1. repo.findAll(Sort.by(Order.asc("empDept"),Order.desc("empSalary")))
2. .forEach(System.out::println);
Note: First it will sort based on “empDept” column then sort based on “empSalary”
column if multiple “empSalary” column values are same.
Chapter-02
Spring Boot Data JPA
---------------
Pagination
---------------
- The process of displaying huge no. of records page by page is called pagination.
- Using findAll() method get all rows from DB table. In case of large/huge number
of records/rows display at client side may not good. That’s why Spring data JPA
provide Pagination Concept.
- PagingAndSortingRepository<T, ID> interface given findAll(Pageable pageable)
method for displaying data page by page.
(Or)
1. PageRequest pageable = PageRequest.of(pageNumber, pageSize);
2. Page<Employee> pageData = repo.findAll(pageable);
3. List<Employee> records= pageData.getContent();
4. records.forEach(System.out::println);
PageRequest.of(1,3)
1. pageData.isEmpty(); // false
2. pageData.isLast(); // false
3. pageData.isFirst(); // false
4. pageData.hasNext(); // true
5. pageData.hasPrevious(); // true
6. pageData.getTotalElements(); //total records 10
7. pageData.getTotalPages(); // 4
8. pageData.getSize(); // page size or how many row per page 3
9. pageData.hasContent(); //get second page 3 records as List<Employee>(D,E,F)
10. pageData.getNumber(); // current page number 1
11. pageData.getNumberOfElements(); //current page how many rows are present 3.
Note: JpaRepository is bit known for performing delete operations through batch
processing. It is bit faster.
Chapter-02
Spring Boot Data JPA
-------------------------
Query by Example
------------------------
- It is used to prepare dynamic query based on data available in entity class object.
- Means if we want to search record based on pk or non pk column/columns like
search patient where name = abc and id =198.
- SQL Query: select * from patient_details where pid = 198 and pname= “abc”;
- In CrudRepository and PagingAndSortingRepository interfaces, there is no
method which full fill this type of requirement. But JpaRepository interface
provide findAll(Example<T>) method.
Coding:
-----------
1. Patient p = new Patient();
2. p.setPid(198);
3. p.setPname(“abc”);
4. Example example = Example.of(p);
5. Repo.findAll(example).forEach(System.out::println);
==================
finder/findBy method
==================
- Define abstract method in repository interface by following certain naming rules.
- The select operation which are not possible using findXXX() methods of pre-
define Interfaces, we can developed these kinds of select operation by using
finder/findBy method.
Syntax:
<return type> findBy <class PropertyName> <conditions> (parameter…)
Note: The table name or column names are not case sensitive but column value is case-
sensitive.
1. interface ResultView{
2. public Integer getMid();
3. public String getMname();
4. }
We cannot add Lombok api @Getter annotation we need getter() method declaration only but not
definition.
Example:
Chapter-02
Spring Boot Data JPA
Step #1: Define one Type Interface having getter methods for excepted properites
1. interface ResultView{
2. public Integer getMid();
3. public String getMname();
4. }
Step #2: Take finder method in Repository(I) that method return type List<ResultView> or
Iterable<ResultView>
1. public interface IMovieRepository extends JpaRepository<Movie, Integer> {
2. public List<ResultView> findByMidGreaterThanEqualAndMidLessThanEqual(int startId, int endId)
3.}
Syntax:
@Query(“HQL/JPQL query (or) Native SQL query”)
<returnType> anyMethodName(paramName)
Where,
- HQL/JPQL Query: Queries are developed using entity class name and properties
names. So, Queries are DB s/w independent.
The underlying ORM s/w converts every HQL/JPQL queries into DB specific
SQL query internally by support Dialect component.
- Native SQL Query: queries are developed using DB table names and table column
names. So, queries are DB s/w dependent.
Disadvantages:
- HQL/JPQL based insert operation is not possible.
- HQL/JPQL based DDL (create table, alter table, drop table… etc.) operation is not
possible.
- HQL/JPQL based PL/SQL procedure and function are not possible.
- If HQL/JPQL query retrieving specific columns from DB table then writing SELECT
keyword is mandatory.
- Example:
SQL >> select emp_name, emp_salary from employee
HQL >> select empName, empSalary from Employee;
HQL/JPQL query with WHERE clause using parameter (positional param, name param):
Coding
1. Public interface IBookRepository extends JpaRepository<Book, Integer>{
2. //SQL: select * from booktab where author=?
3. //@Query("SELECT b FROM Book b WHERE b.author=?1")
4. @Query("SELECT b FROM Book b WHERE b.author = :authorName")
5. List<Book> getBooksByAuthor(String authorName);
6.
7. //SQL: select * from booktab where author like ? or bcost > ?
8. //@Query("SELECT * FROM Book WHERE bookCost > :bookCost OR author like :author")
9. @Query("SELECT * FROM Book WHERE author like ?1 OR bookCost >?2 OR bookType=?3")
10. List<Book> getBooksAuthorCost(String author, Double bookCost, String bType);
11. }
Note: if the query param name do not matching with method param name then use
@Param annotation. Working with named param by matching their names with method
param names is good practice.
Example:
@Query("SELECT b FROM Book b WHERE b.author = :abc")
List<Book> getBooksByAuthor(@Param("abc") String author);
Note: No. of parameters present in Query and no. of parameters present in method
param must be same (same count).
Chapter-02
Spring Boot Data JPA
HQL/JPQL query (selecting all columns value from DB table). Return type List of entity object.
1. public IMovieRepository extends JpaRepository{
2. @Query(“from Movie where mname in(:name1, :name2, : name3)”)
3. List<Movie> searchMovieByName(String name1, String name2, String name3);
4. }
HQL/JPQL query (selecting specific multiple columns value from DB table). Return type List of
object class obj[].
1. public interface IMovieRepository extends JpaRepository<Movie, Integer>{
2. @Query(“select mid, mname, year from Movie where rating >=:rat and year in(:y1, :y2)”)
3. List<Object[]> fetchMovieByRatingAndYear(float rat, String y1, String y2);
4. }
HQL/JPQL query (selecting single column value from DB table). Return type List of
<propertyType>.
1. public IMovieRepository extends JpaRepository<Movie, Integer>{
2. @Query(“select mname from Movie where year in(:y1, :y2, :y3) order by mname desc”)
3. List<String> fetchingMovieByYears(String y1, String y2, String y3);
4. }
Q) When we have readymade method findById(), then why should we use @Query methods
for single row Operations?
Answer:
- The findByAll(-) method can take only pk id value but @Query method for single
row operation we can take other unique column value.
Example: Getting specific single column value of single row/record
1. @Query(“select releaseDate from Movie where mname = :name”)
2. public String fetchingMovieReleaseDateByName(String name)
3.
4. //service class
5. Stirng releaseDate = repo. fetchingMovieReleaseDateByName(“RRR”)
=============================================
Performing Non- select Operation using HQL/JPQL
=============================================
- For non-selecting we need to take @Modifying + @Query(__) methods in our Repository
interface. @Modifying indicates that Query is either UPDATE or DELETE
- If we are taking separate Service layer by using @Service annotation then, placing
@Transactional annotation on top of the Repository interface or interface methods are
optional. Because @Service annotation will take care of Transaction management.
- If we are not taking separate Service layer then we must place @Transaction on top of
the Repository Interface or interface @Query(_) method + @Modifying
- Generally, @Query(_) + @Modifying methods return type int or byte or sort or long
because of non-select HQL/JPQL query return no. of records that are effected in numeric
format.
Chapter-02
Spring Boot Data JPA
Example:
1. @Transactional
2. public IEmployeeRepository extends JpaRepository<Employee, Integer> {
3. @Modifying
4. //@Transactional
5. @Query(“update Employee set address=:address where empId=:id”)
6. public int modifyEmpAddress(String address, Integer id)
7.
8. @Modifying
9. //@Transactional
10. @Query(“delete from Employee where empId=:id”)
11. public int modifyEmpAddress(Integer id)
12. }
=============================
Working with Native SQL Query
=============================
- If certain operations are not possible using readymade methods or finder
methods or @Query(_) methods then prefer to use Native SQL query.
- For that we need to place “nativeQuery=true” in @Query(_) methods and also
we need to add @Modifying and @Transactional annotation.
- Spring data jpa native query support positional param (?, ?, ?), ordinal param (?
1, ?2, ?3) and named param (:name, :id).
- Native query will be written using db table name and columns name that is native
query is db dependent.
1. @Transactional
2. public IEmployeeRepository extends JpaRepository<Employee, Integer> {
3. @Modifying
4. @Query(value=“insert into emp_reg values(mid_seq.NEXTVAL,?,?)”, nativeQuery=true)
5. public int registerEmployee(String empName, double salary);
6.
7. @Modifying
8. @Query(value= “select SysDate from dual”, nativeQuery=true)
9. public String fetchingSystemDate();
10. }
==============================
Working with Collection Mapping
==============================
- For form input types like [text field, radio, password, single select drop down,
text area] create a variable with primitive type like String, Integer, Double, Long,
Float … etc.
- For Form input types like [multi-select dropdown, checkbox for select multiple
options] create variable as collection types (List, Set, Map …etc.)
- In Database concept all primitives are stored as one primary table (Parent table)
and for every collection (List, Set, Map) create separate child tables.
- In ORM
All primitive variables = 1 table
1 primitive variable = 1 column
1 collection variable = 1 child table with 2/3 columns
- We have 2 Types of collections mapping: -
Index Based Collection: (child table - 3 columns) List (Index 0,1,2,3) and
Map (Map Key behaves as index). Because List can contain duplicate value
that’s why index.
Non-Index based Collection: (child table - 2 columns) Set [No index
column here because value is unique]
3 columns:
Key Column (FK Column / Join Column) that is Pk from Parent Table.
Index Column (Optional to config)
Element Column (Data Column)
Chapter-02
Spring Boot Data JPA
Annotations of collection mapping:
1. @ElementCollection [mandatory]
We must apply @ElementCollection annotation on top of every collection
variable. This annotation creates child table for every collection variable with 2/3
columns
2. @CollectionTable [Optional]
To specify child table name
3. @JoinColumn [Optional]
To specify FK column name of child table that is linked with PK column of Parent
table.
Syntax:
@CollectionTable(name= “childTableName”,
joinColumns= @JoinColumn(
name=“FK_col_name”,referencedColumnName= “PkColName”))
4. @OrderColumn (name= “indexColNameForList”) [Optional]
5. @Column (name= “DataColName”) [Optional]
6. @MapKeyColumn (name = “indexColNameForMap”) [Optional]
7. @ListIndexBase(value=1): It specify the start/base value of list index
1. @Entity
2. public class EmployeeInfo {
3. @Id
4. private Integer eid;
5. private String ename;
6.
7. @ElementCollection
8. @CollectionTable(name="emp_info_friends",
9. joinColumns = @JoinColumn(name="eidFk")
10. )
11. @OrderColumn(name="frnd_indx") //index
12. @Column(name="friends_list")
13. private List<String> friends;
14.
15. @ElementCollection
16. @CollectionTable(name="emp_info_phn_num",
17. joinColumns = @JoinColumn(name="eidFk")
18. )
19. @Column(name="phn_num")
20. private Set<String> phnNumber;
21.
22. @ElementCollection //must
23. @CollectionTable(name="emp_info_idcart_dtls",//table name
24. joinColumns = @JoinColumn(name="eidfk")//Fk column
25. )
26. @MapKeyColumn(name="idcart_indx") //index
27. @Column(name="idcart_dtls") //element column
28. private Map<Integer, String> idCartDtls;
29. }
Chapter-02
Spring Boot Data JPA
Providing Collection table name and Columns name are good practice. Using below
naming rules-
1. Child Table name = “parentTableName_ListVariableName”
2. Join column name = “ListVaribaleName_PKColumnName”
3. Data column name = “CollectionVartibaleName”
==================================
Association/HAS-A Relation Mapping
==================================
Example:
emp_id emp_name emp_gender address phone_number number_type
01 AA M xxyy 09800098 personal
01 AA M ZZHh 0293480 home
02 BB F pkiu 0213944 personal
03 CC M rtu 7645333 personal
Personal details in single table Data redundancy problem
To solve this problem, we need to keep two separate table/entities and connect two
tables of entities using PK in parent table and FK in child table.
Chapter-02
Spring Boot Data JPA
The possible association between db tables are
1. One to one
2. One to Many
3. Many to One
4. Many to Many
In java to build association between parent and child entity classes using HAS-A relation.
We can take two types of HAS-A relation for this association mapping in Entity classes.
======================Coding Steps====================================
Step#1: Define two entity classes
Step#2: Apply HAS-A Relation (Created child class variable in Parent class)
Step#3: Check for Collection/Non-Collection type
Step#4: Apply Mapping Annotation and Fk Columns
Step#5: Just draw two tables with sample columns.
Note:
- Do not add @Data Lombok annotation on top of the entity classes in association
mapping because it gives overriding methods like hashCode(), toString(),
equels() ..etc. they may gives problem when storing object in Collections.
- Instead of @Data annotation we can add @Getter, @Setter, @NoArgConstructor,
@AllArgConstructor annotation on top of the Entity classes.
Chapter-02
Spring Boot Data JPA
==========
FetchType
==========
- To fetch data from multiple entities(tables) as EAGER or LAZY format.
- FetchType it is a ENUM provided by JPA with two values: LAZY, EAGER
EAGER
- Fetch Parent class/table records with its connected child class/table records
simultaneously.
- Default eager for 1 to 1 and Many to 1 relationship
LAZY
- Fetch Only Parent class/table data when find__ method is called Do not fetch
child data until it is called externally.
- Default Lazy for 1...* and *...* default type is LAZY.
Example:
@OneToMany(fetch = FetchType.EAGER)
@ManyToOne(fetch = FetchType.LAZY)
=========
Cascading
========
- Apply on non-select operation (delete, update, insert)
-
Aggregation
Sometime child table record exists without parent class record that
is called loose coupling.
Example: Student table and Department table relation. When I
removed student table record along with if I removed department
table record then other student is affected.
Note:
- 1 to many / 1 to 1 Use Cascade type like ALL/PERSIST/DELETE. Because One
parent might have been connected to multiple child’s.
- Many to 1 / Many to Many relations do not use DELETE cascading (we can use
PERSIST/MERGE). Because one child might have been connected to multiple
parent)
==========================
Working with Date and Time
==========================
- To inserting, retrieving DOB, TOB, DOJ, TOJ, record created time, last updated
date time, we need to date, time value.
DOB :: Date of Birth
TOB :: Time of Birth
DOJ :: Date of Joining
TOJ :: Time of Joining
- From java 1.8v new Date and Time API is given
LocalDate: To get/set Date value
LocalTime: to get/set Time value
LocalDateTime: to get/set Date and Time value
Chapter-02
Spring Boot Data JPA
- In Oracle db s/w, the date and time related data types are
Date (for date value only)
Timestamp (for date and time values)
- In MySQL db s/w, the date and time related data types are
Date, time and timestamp
- In entity class we need to define appropriate data type for date and time related
properties like LocalDate, LocalTime, LocalDateTime… etc.
Entity class with java 1.8v date and Time API Coding:
1. @Data
2. @Entity
3. public class PersonalInfo {
4. @Id
5. private Integer pid;
6. private String pname;
7. private LocalDate dob;
8. private LocalTime tob;
9. private LocalDateTime doj;
10. }
Note: only to create variable using java.util.Date package. No need for java
1.8v date and time API.
@CreationTimeStamp: To generate record created date.
@UpdateTimeStamp: To generate record updated date.
Example:
1. @Entity
2. public class Employee {
3.
4. @Id
5. private Integer empId;
6.
7. @Temporal(TemporalType.TIMESTAMP)//(default)
8. private Date dob;
Chapter-02
Spring Boot Data JPA
9.
10. @CreationTimestamp
11. @Column(name="date_created", updatable = false)
12. private LocalDate dateCreated;
13.
14. @UpdateTimestamp
15. @Column(name="last_updated", insertable = false)
16. private LocalDate lastUpdated;
17. }
=========================
Working with Large Objects
=========================
- Large object means files like image files, audio files, video files, text file, movie
files … etc.
- All major DB s/w support Large Objects
- In oracle gives BLOB, CLOB data types for large objects
- In MySQL gives TINYBLOB, BLOB, MEDIUMBLOB, LONGBLOB, Text, Medium Text,
Long Text.
- BLOB means binary files (images, audios, videos, graphics … etc.)
- CLOB means character files (text, csv files, rich text … etc.)
- We need to take byte [] for BLOB data type and char[] for CLOB data type in Entity
class.
- While developing standalone application we store LOBs file directly in db column.
Annotations:
@Lob
private byte [] image
@Lob
private char[] resume
Chapter-02
Spring Boot Data JPA
==============================
Generate Custom Composite Key
==============================
Example:
Entity class
1. @Data
2. @Entity
3. @Table(name="account_tbl")
4. public class Account {
5. private String holderName;
6. private String branch;
7.
8. @EmbeddedId
9. private AccountPK accountPk;
10. }
Repository
1. public interface AccountRepo
2. extends JpaRepository<Account, AccountPK>{
3. }
Chapter-02
Spring Boot Data JPA
==========
Generator
==========
- Ids is PK that is given from application after taking end-user data.
- Generators are two types
Pre-defined Generators
Custom Generators
Pre-defined Generator:
- @GeneratedValue annotation is used with GenerationType.
- GenerationType is ENUM has values are
SEQUENCE
It is mostly used for Oracle databases Object that generate numbers
IDENTITY
It is used for MySQL. (Auto-Increment).
TABLE
A table is created (behaves like sequence) and store id value.
AUTO
Any one option is selected based on DB
------------------------------
Coding: At Entity class
------------------------------
1. @Data
2. @Entity
3. public class Product {
4.
5. @Id
6. @GeneratedValue(strategy = GenerationType.AUTO)// SEQUENCE or IDENTITY
7. @Column(name="pid")
8. private String prodId;
9.
10. @Column(name="pname")
11. private String prodName;
12.
13. @Column(name="pcost")
14. private Double prodCost;
15.
16. }
Chapter-02
Spring Boot Data JPA
(or)
-------------------------------
Coding: At Entity Class
-------------------------------
1. @Data
2. @Entity
3. public class Product {
4.
5. @Id
6. @SequenceGenerator(name= “test” initialValue=1000,
7. allocationSize=1, sequenceName= “pid_seq”)
8. @GeneratedValue(generator= “test”, strategy = GenerationType.SEQUENCE)
9. @Column(name="pid")
10. private String prodId;
11.
12. @Column(name="pname")
13. private String prodName;
14.
15. @Column(name="pcost")
16. private Double prodCost;
17.
18. }
Where,
Generator = “test” is used to link
initialValue = starting from 1000 or our Requirement
allocationSize = increment
sequenceName = db Sequence Object name
--------------------------
Custom Generator:
--------------------------
- We want to generate primary key columns values as per our project requirement
like below-
Example:
OD_1
OD_2
OD_3
……
OD_nth
- To achieve this type of requirement, we need to develop our own generator. That
is called as Custom Generator.
Chapter-02
Spring Boot Data JPA
----------
Coding
----------
1. @Entity
2. @Data
3. public class OrderDetails {
4. @Id
5. @GeneratedValue(generator="order_id")
6. @GenericGenerator(name="order_id",strategy="org.nadim.generator.OrderIdGenerator")
7. private String orderId;
8. }
Chapter-02
Spring Boot Data JPA
Q) How to insert partial data to records or how to perform partial save object
operation?
Example:
1. class student{
2. int sid;
3. String sname;
4. String gender;
5. String dept;
6. String email;
7. }
In this class we want to save student object with Student class properties sid, sname and
dept only. How?
Answer:
- Using save(-) or saveAll(-) methods. But keeping partial data to the given entity
object by making the remaining properties values as NULL or using @Transient
annotation on top of the entity class properties which are we do not want to
save.
Example: using null
Student std = new Student();
std.setSname(“nadim”);
std.setDept(“CES”);
//std.setGender(null); // place null value explicitly is optional
//std.setEmail(null);
repo.save(std);
Q) What is DAO?
Answer: DAO (Data Access Object) is a class that contains code to perform Database
Operations.