SlideShare a Scribd company logo
Spring Data JPA
• What is Spring Data
• Configurations
• Domain/Entities
• Persistent Identity
• Identifier Generation
• Customizing the Entity Object
• Entity Relationships
• Entity Inheritance
• EntityManager & the Persistent
Context
Agenda
• Repository and Repository Hierarchy
• User Defined Repository
• Defining Query methods
• Pageable
• Query creation : Custom Queries and
Named Queries
• Custom Interfaces
• Accessing Spring Data with rest
• Transactional
• Disadvantages
What and Why ?
Spring Data is a high level SpringSource project whose purpose is to unify and ease
the access to different kinds of persistence stores, both relational database systems
and NoSQL data stores.
Features
• Powerful repository and custom object-mapping abstractions
• Dynamic query derivation from repository method names
• Implementation domain base classes providing basic properties
• Support for transparent auditing
• Possibility to integrate custom repository code
• Advanced integration with Spring MVC controllers
• Several modules such as : Spring Data JPA, Spring Data MongoDB, Spring
Data REST, Spring Data Cassandra etc.
3
Dependencies :
compile('mysql:mysql-connector-java:5.1.6')
compile('org.springframework.boot:spring-boot-starter-data-jpa')
Setting :
spring:
datasource:
url: jdbc:mysql://localhost:3306/spring_jpa?autoReconnect=true&useUnicode=true&CharSet=UTF-
8&characterEncoding=UTF-8
username: root
password: igdefault
driverClassName: com.mysql.jdbc.Driver
jpa:
hibernate.ddl-auto: create-drop
show-sql: true
4
Configuration
• An entity is a plain old java object (POJO)
• Requirements:
– annotated with the javax.persistence.Entity annotation
– public or protected, no-argument constructor
– the class must not be declared final
– no methods or persistent instance variables must be declared final
• Entities may extend both entity and non-entity classes
• Persistent instance variables must be declared private, protected
import javax.persistence.*;
@Entity
public class User {
private String email;
private String name;
}
5
Domain/Entities
• Each entity must have a unique object identifier (persistent identifier)
• Identifier (id) in entity = primary key in database
• Example :
import javax.persistence.*;
public class User {
@Id
private Long id;
}
6
Persistent Identity
• Identifiers can be generated in the database by specifying @GeneratedValue on the
identifier
• Four pre-defined generation strategies:
– AUTO,
– IDENTITY,
– SEQUENCE,
– TABLE
• Specifying strategy of AUTO indicates that the provider will choose a strategy
• Example:
import javax.persistence.*;
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
}
7
Identity Generation
• In most of the cases, the defaults are sufficient
• By default the table name corresponds to the unqualified name of the class
• Customization:
@Entity
@Table(name = "user")
public class User {}
• The defaults of columns can be customized using the @Column annotation
@Column(nullable = true, unique = true)
private String email;
@Column(name = "full_name", nullable = false, length = 25)
private String name;
8
Customizing the Entity Object
• There are four types of relationship multiplicities:
– @OneToOne
– @OneToMany
– @ManyToOne
– @ManyToMany
• The direction of a relationship can be:
– bidirectional – owning side and inverse side
– unidirectional – owning side only
• Supports cascading updates/deletes
• You can declare performance strategy to use with fetching related rows
FetchType :
LAZY, EAGER
9
Entity Relationships
10
ManyToOne Mapping
11
OneToMany Mapping
12
ManyToMany Mapping
• Entities can inherit from other entities and from non-entities
• The @Inheritance annotation identifies a mapping strategy:
– SINGLE_TABLE
– JOINED
– TABLE_PER_CLASS
• SINGLE_TABLE strategy - all classes in the hierarchy are mapped to a single table in the
database
• Discriminator column - contains a value that identifies the subclass
• Discriminator type - {STRING, CHAR, INTEGER}
• Discriminator value - value entered into the discriminator column for each entity in a
class hierarchy
13
Entity Inheritance
@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="DISC", discriminatorType=DiscriminatorType.STRING)
@DiscriminatorValue(value="USER")
public class User { . . . }
@Entity
@DiscriminatorValue(value="PUSER")
public class PremiumUser extends User { . . . }
14
Entity Inheritance : Example
• Entities are managed by the entity manager
• The entity manager is represented by javax.persistence.EntityManager instances
• Each EntityManager instance is associated with a persistence context
• A persistence context defines the scope under which particular entity instances are
created, persisted, and removed
• A persistence context is a set of managed entity instances that exist in a particular
data store
– Entities keyed by their persistent identity
– Only one entity with a given persistent identity may exist in the persistence
context
– Entities are added to the persistence context, but are not individually removable
(“detached”)
• Controlled and managed by EntityManager
– Contents of persistence context change as a result of operations on
EntityManager API
15
Managing Entities - JPA
16
Persistence Context
• A lot of code in the persistent framework and the DAO.
• Duplicate code in concrete DAOs
• Pagination need to handle yourself, and integrated from MVC to persistent layer.
• If hybrid database (MySql + Mongo) are required for the system. It is not easy to have
similar design concept in the Architecture.
17
Pains
• The goal of the repository abstraction of Spring Data is to reduce the effort to
implement data access layers for various persistence stores significantly.
• The central marker interface
• Repository<T, ID extends Serializable>
• Hierarchy :
Interface JpaRepository<T, ID>
interface PagingAndSortingRepository<T, ID>
interface CrudRepository<T, ID>
interface Repository<T, ID>
18
Repository and Repository Hierarchy
Spring Data Repository, you’ll have three options:
• Using of a CRUD operations that implemented by the Spring Data
infrastructure
• Defining of a query methods and
• Manually implementing your own custom repositories
• Example :
public interface UserRepository extends JpaRepository<User, Long> {
}
19
User Defined Repository
Query methods implemented in spring data repositories will be used for creating the
dynamic queries.
public interface UserRepository extends JpaRepository<User, Long> {
User findByEmail(String email);
List<User> findAllByName(String name);
}
20
Defining Query methods
Pageable pageable = new PageRequest(0, 10);
Sort.Order order1 = new Sort.Order(Sort.Direction.ASC, "id");
Sort.Order order2 = new Sort.Order(Sort.Direction.DESC, "name");
Sort sort = new Sort(order1, order2);
pageable = new PageRequest(0, 10, sort);
pageable = new PageRequest(0, 10, new Sort(Sort.Direction.DESC, "name"));
21
Pageable
• @Query annotation is used to defining the custom queries in spring data.
• Supports JPQL and native SQL.
• @Param method arguments to bind query parameters.
• Supports SpEL expression.
• Like expression supported inside @Query annotation.
• @Query annotation, this will take the precedence over @NamedQuery
• Examples :
@Query("select u from User u where u.name=?1")
User findByUserName(String name);
@Query("select u from User u where u.name like%:name%")
User findByUserName(@Param("name") String name);
@Query(value = "select * from user where name=?1", nativeQuery = true)
User findByUserName(String name);
22
Query creation : Custom Queries
• Named query are the static queries.
• The named queries are defined in the single place at entity class itself with
each query has its unique name.
• @NamedQuery annotation can be applied only at the class level.
• Named queries have the global scope.
• If you have to define more than one named queries the use @NamedQueries
• All the named queries are validated at application start-up time and there is no
failure at run time.
• Example :
@NamedQuery(name = "User.findByNameNamed", query = "SELECT u
FROM User u WHERE LOWER(u.name) = LOWER(?1)")
@Table(name = "user")
public class User {
…..
}
23
Query creation : Named Queries
• Adding custom behavior to single repositories
Create an interface which declares the custom methods :
public interface UserCustomRepository {
public User customMethod();
}
Implement custom repository :
public class UserRepositoryImpl implements UserCustomRepository {
@Override
public User customMethod() {
}
}
Extend interface:
public interface UserRepository extends JpaRepository<User, Long>, UserCustomRepository {
}
24
Custom Interfaces
• Adding custom behavior to all repositories
Creating a Base Repository Interface :
@NoRepositoryBean
public interface MyRepository<T, ID extends Serializable> extends JpaRepository<T, ID> {
T sharedMethod(ID id);
}
Implementing the Base Repository Interface :
public class MyRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID>
implements MyRepository<T, ID> {
}
25
Custom Interfaces
• Adding custom behavior to all repositories
Creating a Custom RepositoryFactoryBean :
public class MyRepositoryFactoryBean extends JpaRepositoryFactoryBean {
}
Configuring Spring Data JPA :
@EnableJpaRepositories(repositoryFactoryBeanClass = MyRepositoryFactoryBean.class)
26
Custom Interfaces
• Add dependency :
compile("org.springframework.boot:spring-boot-starter-data-rest")
• Annotate repository :
@RepositoryRestResource()
27
Accessing Spring Data with REST
• CRUD methods on repository instances are transactional by default.
• Use @Transactional annotation in repository.
@Transactional(timeout = 10)
@Transactional(readOnly = true)
28
Transactions
Methods name are very long in the complicated structure.
No support for aggregation queries.
29
Disadvantages
springdatajpa-up.pdf
References
31
Samples : https://github.com/jitinjeevesh/spring-jpa
 http://projects.spring.io/spring-data/
 https://dzone.com/articles/easier-jpa-spring-data-jpa
 http://docs.spring.io/spring-data/jpa/docs/current/reference/html/
springdatajpa-up.pdf

More Related Content

What's hot (20)

PPTX
Spring boot - an introduction
Jonathan Holloway
 
PPTX
JPA For Beginner's
NarayanaMurthy Ganashree
 
PDF
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Edureka!
 
PPTX
Spring boot
Gyanendra Yadav
 
PPT
Java Persistence API (JPA) Step By Step
Guo Albert
 
PDF
Java Classes | Java Tutorial for Beginners | Java Classes and Objects | Java ...
Edureka!
 
PPSX
Java &amp; advanced java
BASAVARAJ HUNSHAL
 
PPTX
Java interfaces
jehan1987
 
PDF
Laravel Core Concept & Ecosystem
Mesut Vatansever
 
PDF
Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...
Edureka!
 
PDF
Inheritance In Java
Arnab Bhaumik
 
ODP
Ruby
Aizat Faiz
 
PDF
Ruby Presentation
platico_dev
 
PDF
Java Programming
Anjan Mahanta
 
PPTX
Web container and Apache Tomcat
Auwal Amshi
 
PDF
Spring boot introduction
Rasheed Waraich
 
PDF
Java programming-examples
Mumbai Academisc
 
PDF
Introduction to Spring's Dependency Injection
Richard Paul
 
PDF
Spring Boot and Microservices
seges
 
PPT
hibernate with JPA
Mohammad Faizan
 
Spring boot - an introduction
Jonathan Holloway
 
JPA For Beginner's
NarayanaMurthy Ganashree
 
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Edureka!
 
Spring boot
Gyanendra Yadav
 
Java Persistence API (JPA) Step By Step
Guo Albert
 
Java Classes | Java Tutorial for Beginners | Java Classes and Objects | Java ...
Edureka!
 
Java &amp; advanced java
BASAVARAJ HUNSHAL
 
Java interfaces
jehan1987
 
Laravel Core Concept & Ecosystem
Mesut Vatansever
 
Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...
Edureka!
 
Inheritance In Java
Arnab Bhaumik
 
Ruby Presentation
platico_dev
 
Java Programming
Anjan Mahanta
 
Web container and Apache Tomcat
Auwal Amshi
 
Spring boot introduction
Rasheed Waraich
 
Java programming-examples
Mumbai Academisc
 
Introduction to Spring's Dependency Injection
Richard Paul
 
Spring Boot and Microservices
seges
 
hibernate with JPA
Mohammad Faizan
 

Similar to springdatajpa-up.pdf (20)

PPTX
Spring data jpa
Jeevesh Pandey
 
PDF
S313431 JPA 2.0 Overview
Ludovic Champenois
 
PDF
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
Arun Gupta
 
PDF
Local Storage
Ivano Malavolta
 
PPTX
Android Database
Dr Karthikeyan Periasamy
 
PDF
Jpa
vantinhkhuc
 
PPTX
VB.net&OOP.pptx
BharathiLakshmiAAssi
 
PDF
Google App Engine - exploiting limitations
Tomáš Holas
 
PPTX
L04 base patterns
Ólafur Andri Ragnarsson
 
PDF
Introduction to Datastore
Software Park Thailand
 
PDF
Java Web Programming on Google Cloud Platform [2/3] : Datastore
IMC Institute
 
PDF
Understanding
Arun Gupta
 
PDF
Using the latest Java Persistence API 2.0 features
Arun Gupta
 
PPTX
CodeIgniter & MVC
Jamshid Hashimi
 
PPTX
SQLite Opening .pptx
ImranS18
 
PDF
JAX-RS Creating RESTFul services
Ludovic Champenois
 
PPTX
Examiness hints and tips from the trenches
Ismail Mayat
 
PPTX
Easy data-with-spring-data-jpa
Staples
 
PPT
01-introduction OOPS concepts in C++ JAVA
muraliravisubs
 
PDF
Access Data from XPages with the Relational Controls
Teamstudio
 
Spring data jpa
Jeevesh Pandey
 
S313431 JPA 2.0 Overview
Ludovic Champenois
 
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
Arun Gupta
 
Local Storage
Ivano Malavolta
 
Android Database
Dr Karthikeyan Periasamy
 
VB.net&OOP.pptx
BharathiLakshmiAAssi
 
Google App Engine - exploiting limitations
Tomáš Holas
 
L04 base patterns
Ólafur Andri Ragnarsson
 
Introduction to Datastore
Software Park Thailand
 
Java Web Programming on Google Cloud Platform [2/3] : Datastore
IMC Institute
 
Understanding
Arun Gupta
 
Using the latest Java Persistence API 2.0 features
Arun Gupta
 
CodeIgniter & MVC
Jamshid Hashimi
 
SQLite Opening .pptx
ImranS18
 
JAX-RS Creating RESTFul services
Ludovic Champenois
 
Examiness hints and tips from the trenches
Ismail Mayat
 
Easy data-with-spring-data-jpa
Staples
 
01-introduction OOPS concepts in C++ JAVA
muraliravisubs
 
Access Data from XPages with the Relational Controls
Teamstudio
 
Ad

More from ssuser0562f1 (18)

PDF
Алгоритмы - перебор вариантов и простые задачи
ssuser0562f1
 
PPTX
Jakarta Persistence (JPA) - Web Technologies
ssuser0562f1
 
PDF
Algorithms and programming in Kotlin - 3
ssuser0562f1
 
PDF
Algorithms and programming - lecture no 2
ssuser0562f1
 
PDF
Алгоритмизация и программирование С/С++
ssuser0562f1
 
PDF
Algorithms and programming lecture in ru
ssuser0562f1
 
PDF
Geometry algorithms and formulas calculation
ssuser0562f1
 
PDF
Algorithms in number theory presentation
ssuser0562f1
 
PDF
jpa_nus.pdf
ssuser0562f1
 
PDF
0808.pdf
ssuser0562f1
 
PDF
servlets1.pdf
ssuser0562f1
 
PDF
servlets.pdf
ssuser0562f1
 
PDF
Курсовая (1).pdf
ssuser0562f1
 
PDF
springdatajpatwjug-120527215242-phpapp02.pdf
ssuser0562f1
 
PDF
08-170327133157.pdf
ssuser0562f1
 
PDF
waits.pdf
ssuser0562f1
 
PDF
waits.pdf
ssuser0562f1
 
PDF
geometry.pdf
ssuser0562f1
 
Алгоритмы - перебор вариантов и простые задачи
ssuser0562f1
 
Jakarta Persistence (JPA) - Web Technologies
ssuser0562f1
 
Algorithms and programming in Kotlin - 3
ssuser0562f1
 
Algorithms and programming - lecture no 2
ssuser0562f1
 
Алгоритмизация и программирование С/С++
ssuser0562f1
 
Algorithms and programming lecture in ru
ssuser0562f1
 
Geometry algorithms and formulas calculation
ssuser0562f1
 
Algorithms in number theory presentation
ssuser0562f1
 
jpa_nus.pdf
ssuser0562f1
 
0808.pdf
ssuser0562f1
 
servlets1.pdf
ssuser0562f1
 
servlets.pdf
ssuser0562f1
 
Курсовая (1).pdf
ssuser0562f1
 
springdatajpatwjug-120527215242-phpapp02.pdf
ssuser0562f1
 
08-170327133157.pdf
ssuser0562f1
 
waits.pdf
ssuser0562f1
 
waits.pdf
ssuser0562f1
 
geometry.pdf
ssuser0562f1
 
Ad

Recently uploaded (20)

PPTX
Top 10 AI Tools, Like ChatGPT. You Must Learn In 2025
Digilearnings
 
PPTX
Virus sequence retrieval from NCBI database
yamunaK13
 
PPTX
Command Palatte in Odoo 18.1 Spreadsheet - Odoo Slides
Celine George
 
PDF
My Thoughts On Q&A- A Novel By Vikas Swarup
Niharika
 
PPTX
CONCEPT OF CHILD CARE. pptx
AneetaSharma15
 
PPTX
Digital Professionalism and Interpersonal Competence
rutvikgediya1
 
PPTX
Gupta Art & Architecture Temple and Sculptures.pptx
Virag Sontakke
 
PPTX
ENGLISH 8 WEEK 3 Q1 - Analyzing the linguistic, historical, andor biographica...
OliverOllet
 
PDF
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
PDF
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
Nguyen Thanh Tu Collection
 
PPTX
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
PPTX
Applied-Statistics-1.pptx hardiba zalaaa
hardizala899
 
PDF
EXCRETION-STRUCTURE OF NEPHRON,URINE FORMATION
raviralanaresh2
 
PPTX
LDP-2 UNIT 4 Presentation for practical.pptx
abhaypanchal2525
 
PPTX
Cybersecurity: How to Protect your Digital World from Hackers
vaidikpanda4
 
PDF
TOP 10 AI TOOLS YOU MUST LEARN TO SURVIVE IN 2025 AND ABOVE
digilearnings.com
 
PPTX
YSPH VMOC Special Report - Measles Outbreak Southwest US 7-20-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
PPTX
The Future of Artificial Intelligence Opportunities and Risks Ahead
vaghelajayendra784
 
PPTX
Introduction to Probability(basic) .pptx
purohitanuj034
 
PPTX
Sonnet 130_ My Mistress’ Eyes Are Nothing Like the Sun By William Shakespear...
DhatriParmar
 
Top 10 AI Tools, Like ChatGPT. You Must Learn In 2025
Digilearnings
 
Virus sequence retrieval from NCBI database
yamunaK13
 
Command Palatte in Odoo 18.1 Spreadsheet - Odoo Slides
Celine George
 
My Thoughts On Q&A- A Novel By Vikas Swarup
Niharika
 
CONCEPT OF CHILD CARE. pptx
AneetaSharma15
 
Digital Professionalism and Interpersonal Competence
rutvikgediya1
 
Gupta Art & Architecture Temple and Sculptures.pptx
Virag Sontakke
 
ENGLISH 8 WEEK 3 Q1 - Analyzing the linguistic, historical, andor biographica...
OliverOllet
 
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
Nguyen Thanh Tu Collection
 
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
Applied-Statistics-1.pptx hardiba zalaaa
hardizala899
 
EXCRETION-STRUCTURE OF NEPHRON,URINE FORMATION
raviralanaresh2
 
LDP-2 UNIT 4 Presentation for practical.pptx
abhaypanchal2525
 
Cybersecurity: How to Protect your Digital World from Hackers
vaidikpanda4
 
TOP 10 AI TOOLS YOU MUST LEARN TO SURVIVE IN 2025 AND ABOVE
digilearnings.com
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 7-20-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
The Future of Artificial Intelligence Opportunities and Risks Ahead
vaghelajayendra784
 
Introduction to Probability(basic) .pptx
purohitanuj034
 
Sonnet 130_ My Mistress’ Eyes Are Nothing Like the Sun By William Shakespear...
DhatriParmar
 

springdatajpa-up.pdf

  • 2. • What is Spring Data • Configurations • Domain/Entities • Persistent Identity • Identifier Generation • Customizing the Entity Object • Entity Relationships • Entity Inheritance • EntityManager & the Persistent Context Agenda • Repository and Repository Hierarchy • User Defined Repository • Defining Query methods • Pageable • Query creation : Custom Queries and Named Queries • Custom Interfaces • Accessing Spring Data with rest • Transactional • Disadvantages
  • 3. What and Why ? Spring Data is a high level SpringSource project whose purpose is to unify and ease the access to different kinds of persistence stores, both relational database systems and NoSQL data stores. Features • Powerful repository and custom object-mapping abstractions • Dynamic query derivation from repository method names • Implementation domain base classes providing basic properties • Support for transparent auditing • Possibility to integrate custom repository code • Advanced integration with Spring MVC controllers • Several modules such as : Spring Data JPA, Spring Data MongoDB, Spring Data REST, Spring Data Cassandra etc. 3
  • 4. Dependencies : compile('mysql:mysql-connector-java:5.1.6') compile('org.springframework.boot:spring-boot-starter-data-jpa') Setting : spring: datasource: url: jdbc:mysql://localhost:3306/spring_jpa?autoReconnect=true&useUnicode=true&CharSet=UTF- 8&characterEncoding=UTF-8 username: root password: igdefault driverClassName: com.mysql.jdbc.Driver jpa: hibernate.ddl-auto: create-drop show-sql: true 4 Configuration
  • 5. • An entity is a plain old java object (POJO) • Requirements: – annotated with the javax.persistence.Entity annotation – public or protected, no-argument constructor – the class must not be declared final – no methods or persistent instance variables must be declared final • Entities may extend both entity and non-entity classes • Persistent instance variables must be declared private, protected import javax.persistence.*; @Entity public class User { private String email; private String name; } 5 Domain/Entities
  • 6. • Each entity must have a unique object identifier (persistent identifier) • Identifier (id) in entity = primary key in database • Example : import javax.persistence.*; public class User { @Id private Long id; } 6 Persistent Identity
  • 7. • Identifiers can be generated in the database by specifying @GeneratedValue on the identifier • Four pre-defined generation strategies: – AUTO, – IDENTITY, – SEQUENCE, – TABLE • Specifying strategy of AUTO indicates that the provider will choose a strategy • Example: import javax.persistence.*; public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; } 7 Identity Generation
  • 8. • In most of the cases, the defaults are sufficient • By default the table name corresponds to the unqualified name of the class • Customization: @Entity @Table(name = "user") public class User {} • The defaults of columns can be customized using the @Column annotation @Column(nullable = true, unique = true) private String email; @Column(name = "full_name", nullable = false, length = 25) private String name; 8 Customizing the Entity Object
  • 9. • There are four types of relationship multiplicities: – @OneToOne – @OneToMany – @ManyToOne – @ManyToMany • The direction of a relationship can be: – bidirectional – owning side and inverse side – unidirectional – owning side only • Supports cascading updates/deletes • You can declare performance strategy to use with fetching related rows FetchType : LAZY, EAGER 9 Entity Relationships
  • 13. • Entities can inherit from other entities and from non-entities • The @Inheritance annotation identifies a mapping strategy: – SINGLE_TABLE – JOINED – TABLE_PER_CLASS • SINGLE_TABLE strategy - all classes in the hierarchy are mapped to a single table in the database • Discriminator column - contains a value that identifies the subclass • Discriminator type - {STRING, CHAR, INTEGER} • Discriminator value - value entered into the discriminator column for each entity in a class hierarchy 13 Entity Inheritance
  • 14. @Entity @Inheritance(strategy=InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name="DISC", discriminatorType=DiscriminatorType.STRING) @DiscriminatorValue(value="USER") public class User { . . . } @Entity @DiscriminatorValue(value="PUSER") public class PremiumUser extends User { . . . } 14 Entity Inheritance : Example
  • 15. • Entities are managed by the entity manager • The entity manager is represented by javax.persistence.EntityManager instances • Each EntityManager instance is associated with a persistence context • A persistence context defines the scope under which particular entity instances are created, persisted, and removed • A persistence context is a set of managed entity instances that exist in a particular data store – Entities keyed by their persistent identity – Only one entity with a given persistent identity may exist in the persistence context – Entities are added to the persistence context, but are not individually removable (“detached”) • Controlled and managed by EntityManager – Contents of persistence context change as a result of operations on EntityManager API 15 Managing Entities - JPA
  • 17. • A lot of code in the persistent framework and the DAO. • Duplicate code in concrete DAOs • Pagination need to handle yourself, and integrated from MVC to persistent layer. • If hybrid database (MySql + Mongo) are required for the system. It is not easy to have similar design concept in the Architecture. 17 Pains
  • 18. • The goal of the repository abstraction of Spring Data is to reduce the effort to implement data access layers for various persistence stores significantly. • The central marker interface • Repository<T, ID extends Serializable> • Hierarchy : Interface JpaRepository<T, ID> interface PagingAndSortingRepository<T, ID> interface CrudRepository<T, ID> interface Repository<T, ID> 18 Repository and Repository Hierarchy
  • 19. Spring Data Repository, you’ll have three options: • Using of a CRUD operations that implemented by the Spring Data infrastructure • Defining of a query methods and • Manually implementing your own custom repositories • Example : public interface UserRepository extends JpaRepository<User, Long> { } 19 User Defined Repository
  • 20. Query methods implemented in spring data repositories will be used for creating the dynamic queries. public interface UserRepository extends JpaRepository<User, Long> { User findByEmail(String email); List<User> findAllByName(String name); } 20 Defining Query methods
  • 21. Pageable pageable = new PageRequest(0, 10); Sort.Order order1 = new Sort.Order(Sort.Direction.ASC, "id"); Sort.Order order2 = new Sort.Order(Sort.Direction.DESC, "name"); Sort sort = new Sort(order1, order2); pageable = new PageRequest(0, 10, sort); pageable = new PageRequest(0, 10, new Sort(Sort.Direction.DESC, "name")); 21 Pageable
  • 22. • @Query annotation is used to defining the custom queries in spring data. • Supports JPQL and native SQL. • @Param method arguments to bind query parameters. • Supports SpEL expression. • Like expression supported inside @Query annotation. • @Query annotation, this will take the precedence over @NamedQuery • Examples : @Query("select u from User u where u.name=?1") User findByUserName(String name); @Query("select u from User u where u.name like%:name%") User findByUserName(@Param("name") String name); @Query(value = "select * from user where name=?1", nativeQuery = true) User findByUserName(String name); 22 Query creation : Custom Queries
  • 23. • Named query are the static queries. • The named queries are defined in the single place at entity class itself with each query has its unique name. • @NamedQuery annotation can be applied only at the class level. • Named queries have the global scope. • If you have to define more than one named queries the use @NamedQueries • All the named queries are validated at application start-up time and there is no failure at run time. • Example : @NamedQuery(name = "User.findByNameNamed", query = "SELECT u FROM User u WHERE LOWER(u.name) = LOWER(?1)") @Table(name = "user") public class User { ….. } 23 Query creation : Named Queries
  • 24. • Adding custom behavior to single repositories Create an interface which declares the custom methods : public interface UserCustomRepository { public User customMethod(); } Implement custom repository : public class UserRepositoryImpl implements UserCustomRepository { @Override public User customMethod() { } } Extend interface: public interface UserRepository extends JpaRepository<User, Long>, UserCustomRepository { } 24 Custom Interfaces
  • 25. • Adding custom behavior to all repositories Creating a Base Repository Interface : @NoRepositoryBean public interface MyRepository<T, ID extends Serializable> extends JpaRepository<T, ID> { T sharedMethod(ID id); } Implementing the Base Repository Interface : public class MyRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements MyRepository<T, ID> { } 25 Custom Interfaces
  • 26. • Adding custom behavior to all repositories Creating a Custom RepositoryFactoryBean : public class MyRepositoryFactoryBean extends JpaRepositoryFactoryBean { } Configuring Spring Data JPA : @EnableJpaRepositories(repositoryFactoryBeanClass = MyRepositoryFactoryBean.class) 26 Custom Interfaces
  • 27. • Add dependency : compile("org.springframework.boot:spring-boot-starter-data-rest") • Annotate repository : @RepositoryRestResource() 27 Accessing Spring Data with REST
  • 28. • CRUD methods on repository instances are transactional by default. • Use @Transactional annotation in repository. @Transactional(timeout = 10) @Transactional(readOnly = true) 28 Transactions
  • 29. Methods name are very long in the complicated structure. No support for aggregation queries. 29 Disadvantages
  • 31. References 31 Samples : https://github.com/jitinjeevesh/spring-jpa  http://projects.spring.io/spring-data/  https://dzone.com/articles/easier-jpa-spring-data-jpa  http://docs.spring.io/spring-data/jpa/docs/current/reference/html/