SlideShare a Scribd company logo
1 of 32
Spring Data JPA
- By Jeevesh Pandey
• 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
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/
Spring data jpa

More Related Content

What's hot

JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring DataArturs Drozdovs
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - CoreDzmitry Naskou
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot IntroductionJeevesh Pandey
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepGuo Albert
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOPDzmitry Naskou
 
Spring framework Controllers and Annotations
Spring framework   Controllers and AnnotationsSpring framework   Controllers and Annotations
Spring framework Controllers and AnnotationsAnuj Singh Rajput
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API07.pallav
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Hitesh-Java
 
Spring Framework - Spring Security
Spring Framework - Spring SecuritySpring Framework - Spring Security
Spring Framework - Spring SecurityDzmitry Naskou
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!Jakub Kubrynski
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentationJohn Slick
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introductionRasheed Waraich
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVCDzmitry Naskou
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate pptAneega
 
Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introductionJonathan Holloway
 

What's hot (20)

JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring Data
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
 
Spring framework Controllers and Annotations
Spring framework   Controllers and AnnotationsSpring framework   Controllers and Annotations
Spring framework Controllers and Annotations
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
 
Spring Framework - Spring Security
Spring Framework - Spring SecuritySpring Framework - Spring Security
Spring Framework - Spring Security
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentation
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
Spring Security 5
Spring Security 5Spring Security 5
Spring Security 5
 
Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introduction
 

Viewers also liked

Easy data-with-spring-data-jpa
Easy data-with-spring-data-jpaEasy data-with-spring-data-jpa
Easy data-with-spring-data-jpaStaples
 
Spring + JPA + DAO Step by Step
Spring + JPA + DAO Step by StepSpring + JPA + DAO Step by Step
Spring + JPA + DAO Step by StepGuo Albert
 
Java Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief OverviewJava Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief OverviewCraig Dickson
 
Lazy vs. Eager Loading Strategies in JPA 2.1
Lazy vs. Eager Loading Strategies in JPA 2.1Lazy vs. Eager Loading Strategies in JPA 2.1
Lazy vs. Eager Loading Strategies in JPA 2.1Patrycja Wegrzynowicz
 
Secure Authentication and Session Management in Java EE
Secure Authentication and Session Management in Java EESecure Authentication and Session Management in Java EE
Secure Authentication and Session Management in Java EEPatrycja Wegrzynowicz
 
Spring Boot. Boot up your development
Spring Boot. Boot up your developmentSpring Boot. Boot up your development
Spring Boot. Boot up your developmentStrannik_2013
 
Jpa with spring data
Jpa with spring dataJpa with spring data
Jpa with spring dataSean Lee
 
Spring.Boot up your development
Spring.Boot up your developmentSpring.Boot up your development
Spring.Boot up your developmentStrannik_2013
 
Implementing Web Services In Java
Implementing Web Services In JavaImplementing Web Services In Java
Implementing Web Services In JavaEdureka!
 
Amazon Webservices for Java Developers - UCI Webinar
Amazon Webservices for Java Developers - UCI WebinarAmazon Webservices for Java Developers - UCI Webinar
Amazon Webservices for Java Developers - UCI WebinarCraig Dickson
 

Viewers also liked (20)

Easy data-with-spring-data-jpa
Easy data-with-spring-data-jpaEasy data-with-spring-data-jpa
Easy data-with-spring-data-jpa
 
Spring + JPA + DAO Step by Step
Spring + JPA + DAO Step by StepSpring + JPA + DAO Step by Step
Spring + JPA + DAO Step by Step
 
Spring Data Jpa
Spring Data JpaSpring Data Jpa
Spring Data Jpa
 
Java Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief OverviewJava Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief Overview
 
Thinking Beyond ORM in JPA
Thinking Beyond ORM in JPAThinking Beyond ORM in JPA
Thinking Beyond ORM in JPA
 
Hibernate using jpa
Hibernate using jpaHibernate using jpa
Hibernate using jpa
 
Lazy vs. Eager Loading Strategies in JPA 2.1
Lazy vs. Eager Loading Strategies in JPA 2.1Lazy vs. Eager Loading Strategies in JPA 2.1
Lazy vs. Eager Loading Strategies in JPA 2.1
 
Colloquium Report
Colloquium ReportColloquium Report
Colloquium Report
 
Secure Authentication and Session Management in Java EE
Secure Authentication and Session Management in Java EESecure Authentication and Session Management in Java EE
Secure Authentication and Session Management in Java EE
 
Spring Boot. Boot up your development
Spring Boot. Boot up your developmentSpring Boot. Boot up your development
Spring Boot. Boot up your development
 
Jpa with spring data
Jpa with spring dataJpa with spring data
Jpa with spring data
 
Java persistence api 2.1
Java persistence api 2.1Java persistence api 2.1
Java persistence api 2.1
 
JPA For Beginner's
JPA For Beginner'sJPA For Beginner's
JPA For Beginner's
 
Second Level Cache in JPA Explained
Second Level Cache in JPA ExplainedSecond Level Cache in JPA Explained
Second Level Cache in JPA Explained
 
JPA - Beyond copy-paste
JPA - Beyond copy-pasteJPA - Beyond copy-paste
JPA - Beyond copy-paste
 
Spring.Boot up your development
Spring.Boot up your developmentSpring.Boot up your development
Spring.Boot up your development
 
Implementing Web Services In Java
Implementing Web Services In JavaImplementing Web Services In Java
Implementing Web Services In Java
 
Spring
SpringSpring
Spring
 
Spring Data Jpa
Spring Data JpaSpring Data Jpa
Spring Data Jpa
 
Amazon Webservices for Java Developers - UCI Webinar
Amazon Webservices for Java Developers - UCI WebinarAmazon Webservices for Java Developers - UCI Webinar
Amazon Webservices for Java Developers - UCI Webinar
 

Similar to Spring data jpa

springdatajpa-up.pdf
springdatajpa-up.pdfspringdatajpa-up.pdf
springdatajpa-up.pdfssuser0562f1
 
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
Using the latest Java Persistence API 2 Features - Tech Days 2010 IndiaUsing the latest Java Persistence API 2 Features - Tech Days 2010 India
Using the latest Java Persistence API 2 Features - Tech Days 2010 IndiaArun Gupta
 
Google App Engine - exploiting limitations
Google App Engine - exploiting limitationsGoogle App Engine - exploiting limitations
Google App Engine - exploiting limitationsTomáš Holas
 
Java Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreJava Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreIMC Institute
 
JAX-RS Creating RESTFul services
JAX-RS Creating RESTFul servicesJAX-RS Creating RESTFul services
JAX-RS Creating RESTFul servicesLudovic Champenois
 
SQLite Opening .pptx
SQLite Opening .pptxSQLite Opening .pptx
SQLite Opening .pptxImranS18
 
RESTful Web services using JAX-RS
RESTful Web services using JAX-RSRESTful Web services using JAX-RS
RESTful Web services using JAX-RSArun Gupta
 
Android App Development 05 : Saving Data
Android App Development 05 : Saving DataAndroid App Development 05 : Saving Data
Android App Development 05 : Saving DataAnuchit Chalothorn
 
Examiness hints and tips from the trenches
Examiness hints and tips from the trenchesExaminess hints and tips from the trenches
Examiness hints and tips from the trenchesIsmail Mayat
 
Using the latest Java Persistence API 2.0 features
Using the latest Java Persistence API 2.0 featuresUsing the latest Java Persistence API 2.0 features
Using the latest Java Persistence API 2.0 featuresArun Gupta
 
Understanding
Understanding Understanding
Understanding Arun Gupta
 
Spark IT 2011 - Context & Dependency Injection in the Java EE 6 Ecosystem
Spark IT 2011 - Context & Dependency Injection in the Java EE 6 EcosystemSpark IT 2011 - Context & Dependency Injection in the Java EE 6 Ecosystem
Spark IT 2011 - Context & Dependency Injection in the Java EE 6 EcosystemArun Gupta
 

Similar to Spring data jpa (20)

springdatajpa-up.pdf
springdatajpa-up.pdfspringdatajpa-up.pdf
springdatajpa-up.pdf
 
Local Storage
Local StorageLocal Storage
Local Storage
 
S313431 JPA 2.0 Overview
S313431 JPA 2.0 OverviewS313431 JPA 2.0 Overview
S313431 JPA 2.0 Overview
 
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
Using the latest Java Persistence API 2 Features - Tech Days 2010 IndiaUsing the latest Java Persistence API 2 Features - Tech Days 2010 India
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
 
Google App Engine - exploiting limitations
Google App Engine - exploiting limitationsGoogle App Engine - exploiting limitations
Google App Engine - exploiting limitations
 
Android Database
Android DatabaseAndroid Database
Android Database
 
Introduction to Datastore
Introduction to DatastoreIntroduction to Datastore
Introduction to Datastore
 
Java Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreJava Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : Datastore
 
L04 base patterns
L04 base patternsL04 base patterns
L04 base patterns
 
Jpa
JpaJpa
Jpa
 
JAX-RS Creating RESTFul services
JAX-RS Creating RESTFul servicesJAX-RS Creating RESTFul services
JAX-RS Creating RESTFul services
 
VB.net&OOP.pptx
VB.net&OOP.pptxVB.net&OOP.pptx
VB.net&OOP.pptx
 
SQLite Opening .pptx
SQLite Opening .pptxSQLite Opening .pptx
SQLite Opening .pptx
 
RESTful Web services using JAX-RS
RESTful Web services using JAX-RSRESTful Web services using JAX-RS
RESTful Web services using JAX-RS
 
Android App Development 05 : Saving Data
Android App Development 05 : Saving DataAndroid App Development 05 : Saving Data
Android App Development 05 : Saving Data
 
Examiness hints and tips from the trenches
Examiness hints and tips from the trenchesExaminess hints and tips from the trenches
Examiness hints and tips from the trenches
 
CodeIgniter & MVC
CodeIgniter & MVCCodeIgniter & MVC
CodeIgniter & MVC
 
Using the latest Java Persistence API 2.0 features
Using the latest Java Persistence API 2.0 featuresUsing the latest Java Persistence API 2.0 features
Using the latest Java Persistence API 2.0 features
 
Understanding
Understanding Understanding
Understanding
 
Spark IT 2011 - Context & Dependency Injection in the Java EE 6 Ecosystem
Spark IT 2011 - Context & Dependency Injection in the Java EE 6 EcosystemSpark IT 2011 - Context & Dependency Injection in the Java EE 6 Ecosystem
Spark IT 2011 - Context & Dependency Injection in the Java EE 6 Ecosystem
 

Recently uploaded

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 

Recently uploaded (20)

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 

Spring data jpa

  • 1. Spring Data JPA - By Jeevesh Pandey
  • 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
  • 30.
  • 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/