SlideShare une entreprise Scribd logo
1  sur  26
Easy Data with
Spring-Data JPA
Miya W. Longwe, Tech Lead, Staples Inc.
January 07, 2014
Java Meetup Group, Cambridge, MA , USA
Agenda
 Java DB Access Ordeal
 Enter Spring-Data
 Spring-Data JPA Features
 Code Demo
 Q and A
Java DB Access
The Developer’s Holy Pilgrim!
Application Domain
 Domain driven design has become a
ubiquitous approach to tackle
complex problem domains and build
a rich object model.
 Implementing a data access layer of
an application has been cumbersome
for quite a while.
 Too much boilerplate code has to be
written.
 Code to execute simple queries as
well as perform pagination, auditing,
etc
Java DB Access – Accessor
Interface
public interface CustomerService {
Customer findById(Long id);
Customer save(Customer customer);
List<Customer> findAll();
List<Customer> findAll(int page, int pageSize);
...
}
Java DB Access –
The Boilerplate Code
/**
* Plain JPA implementation of {@link CustomerService}.
*
* @author Miya W Longwe
*/
@Repository
@Transactional(readOnly = true)
public class CustomerServiceImpl implements CustomerService {
@PersistenceContext
private EntityManager em;
@Override
public Customer findById(Long id) {
return em.find(Customer.class, id);
}
@Override
public List<Customer> findAll() {
return em.createQuery("select c from Customer c", Customer.class).getResultList();
}
……
}
Java DB Access – The Story
● JPA handles mechanics of ORM
● The catch:
– You are responsible for accessor
boilerplate code
● Using direct JDBC?
– More boilerplate code (think DAO
layer)
● What about Spring support?
– Makes things better (JdbcTemplate)
– Spring-Data eases the pain further
Spring-Data to the Rescue!
Spring-Data
 Uses the Repository abstraction for
data access
 Automation of data access
boilerplate code
 Reduces level of efforts for accessor
code
 Support for multiple data stores
including– JPA– Key-Value, column,
document, graph data stores(Redis,
Mongo, Neo4j, HBase)– Hadoop /
HDFS – Others
Spring-Data JPA Workflow
 Define an Entity Class
 Define a Repository interface with
data accessor methods
 Then see you gator!
Define Your Entity
/**
* An entity class which contains the information of a single person.
* @author Miya W. Longwe
*/
@Entity
@Table(name = "persons")
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "creation_time", nullable = false)
private Date creationTime;
@Column(name = "first_name", nullable = false)
private String firstName;
@Column(name = "last_name", nullable = false)
private String lastName;
@Column(name = "modification_time", nullable = false)
private Date modificationTime;
...}
Define The Repository
Interface
 You provide a Java interface
 – Attach an entity type along with key type
 – CRUD/data accessor method signatures
 Spring-Data can automatically derive
proper JPQL
 In simpler cases, no additional code
required
 Queries are derived from method
signatures
Repository Interface
* Specifies methods used to obtain and
modify person related information
* which is stored in the database.
* @author Miya W. Longwe
*/
public interface PersonRepository
extends JpaRepository<Person, Long> {
}
No More Boilerplate Code
 It goes away (sort of) *
 Spring-Data framework derives and
attaches JPQL (or specified query) at
load-time
Spring-Data Features
Provided Repositories
 Spring-Data JPA provides two
repositories
 CrudRepository
– Long list of standard CRUD operations
provided
– findOne(), findAll(), save(), delete(),
exists(), etc
 PagingAndSortingRepository
– Derived from CrudRepository
– Provides paginated repository
access methods
Configure Spring Framework
 Specify your repository locations for
scanning
 Spring will create proxy instances
for repositories
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http:/www.springframework.org/schema/beans"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<mvc:resources mapping="/static/**" location="/static/"/>
<mvc:default-servlet-handler/>
<!--
Configures Spring Data JPA and sets the base package of my DAOs.
-->
<jpa:repositories base-package="com.meetup.easydata.spring.datajpa.repository"/>
</beans>
Spring-Data Query Generation
 Derived from method signatures
 Parses method names for attributes and
keywords
 Uses method parameters as query params
public interface UserRepository extends CrudRepository<User, Long> {
List<Customer> findByEmailAddressAndLastname(String emailAddress, String
lastname);
}
Select c from Customer where c.emailAddress = ?1
and c.lastName = ?2
Spring-Data
Method Name-to-JPQL Mapping
Method Name Generated JPQL
findByXxxAndYyy(aaa,
bbb)
... where t.xxx = ?1 and
t.yyy = ?2
findByXxxOrYyy(aaa,
bbb)
... where t.xxx = ?1 or
t.yyy = ?2
findByXxxStartingWith(a
aa)
('%' appended to param
value)
findByXxxNot(aaa) ... where t.xxx <> ?1
findByXxxIn(Collection<
E>aaa)
...where t.xxx in ?1
---and many more!
Spring-Data
Further Property Parsing Features
-Traversal can reach into nested properties
-Will do best effort using camelCase
-You can delineate properties using “_”
}
@Entity
public class User <Long> {
private ZiCode zicode;
--}
}
public interface UserRepository extends
CrudRepository<User, Long>{
...
User findByAddress_ZipCode(ZipCode zipCode);
@Query – Use Your Own
Query
• You don't like the derived query or want to do
something fancier?
● Use @Query notation to provide your own
● Support both JPQL or native SQL
● Still provides automatic proxy implementation
public interface UserRepository extends CrudRepository<User,
Long>{
...
@Query("select u from User u where u.firstname = ?1")
List<User> findByFirstname(String firstname);
@Query(value="SELECT FROM USERS WHERE
EMAIL_ADDRESS = ?1" nativeQuery=true)
User findByEmailAddress(String email);
...
@Query – Named Params
• Spring-Data JPA will use position for parameter binding
• You can also use named params instead
interface UserRepository extends CrudRepository<User,
Long>{
...
@Query("select u from User u where u.firstname = :name
or u.lastname = :name")
List<User> findByFirstnameOrLastname(@Param("name")
String name);
...
}
Result Pagination
• Seamlessly provides support for result set pagination
via Pageable Interface
• Define repository method with Pageable
• Call method with PageRequest class (or define your
own)
public interface ProductRepository extends CrudRepository<User, Long>{
...
Page<Product> findAll(Pageable pageable);
...
}
class ProductService {
Pageable pageable = new PageRequest(1, 20);
Page<Product> page = repository.findByDescriptionContaining(pageable);
}
Custom Repositories
• When Spring-Data JPA derived queries are not
• enough or you need additional logic
• Provide your own repository implementation
• A bean that lives in Spring Context
interface UserRepositoryCustom {
List<User> myCustomBatchOperation();
}
class UserRepositoryImpl implements UserRepositoryCustom {
@PersistenceContext
private EntityManager em;
public List<User> myCustomBatchOperation() {
CriteriaQuery<User> criteriaQuery = em.getCriteriaBuilder().createQuery(User.class);
return em.createQuery(criteriaQuery).getResultList();
}
}
Transaction Support
• Repository classes are transactional by default
• Reads are made readOnly
• Other methods are @Transactional by default
• Ability to override by providing your own
@Transactional demarcation
public interface UserRepository extends CrudRepository<User, Long>{
...
@Transactional(timeout=10)
@Modifying
@Query("update User u set u.firstname = ?1 where u.lastname = ?2")
User fixFirstNameByLastName(String firstname, String lastname);
...
}
Code Demo

Contenu connexe

Tendances

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-presentation
John Slick
 
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
Guo Albert
 

Tendances (20)

Spring boot
Spring bootSpring boot
Spring boot
 
Lombok
LombokLombok
Lombok
 
Deep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UKDeep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UK
 
Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introduction
 
Rest api with node js and express
Rest api with node js and expressRest api with node js and express
Rest api with node js and express
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
 
Spring jdbc
Spring jdbcSpring jdbc
Spring jdbc
 
Introduction to gradle
Introduction to gradleIntroduction to gradle
Introduction to gradle
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Spring User Guide
Spring User GuideSpring User Guide
Spring User Guide
 
Project Lombok!
Project Lombok!Project Lombok!
Project Lombok!
 
Spring Core
Spring CoreSpring Core
Spring Core
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentation
 
JDBC
JDBCJDBC
JDBC
 
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
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 

En vedette

Spring + JPA + DAO Step by Step
Spring + JPA + DAO Step by StepSpring + JPA + DAO Step by Step
Spring + JPA + DAO Step by Step
Guo Albert
 
Jpa with spring data
Jpa with spring dataJpa with spring data
Jpa with spring data
Sean Lee
 
Data Access 2.0? Please welcome, Spring Data!
Data Access 2.0? Please welcome, Spring Data!Data Access 2.0? Please welcome, Spring Data!
Data Access 2.0? Please welcome, Spring Data!
Oliver Gierke
 
JPQL/ JPA Activity 1
JPQL/ JPA Activity 1JPQL/ JPA Activity 1
JPQL/ JPA Activity 1
SFI
 
Web Services Part 2
Web Services Part 2Web Services Part 2
Web Services Part 2
patinijava
 
JPQL/ JPA Activity 2
JPQL/ JPA Activity 2JPQL/ JPA Activity 2
JPQL/ JPA Activity 2
SFI
 
Patni Hibernate
Patni   HibernatePatni   Hibernate
Patni Hibernate
patinijava
 
JPQL/ JPA Activity 3
JPQL/ JPA  Activity 3JPQL/ JPA  Activity 3
JPQL/ JPA Activity 3
SFI
 

En vedette (20)

Spring Data - Intro (Odessa Java TechTalks)
Spring Data - Intro (Odessa Java TechTalks)Spring Data - Intro (Odessa Java TechTalks)
Spring Data - Intro (Odessa Java TechTalks)
 
Spring Data Jpa
Spring Data JpaSpring Data Jpa
Spring Data Jpa
 
An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring Data
 
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
 
Java and services code lab spring boot and spring data using mongo db
Java and services code lab spring boot and spring data using mongo dbJava and services code lab spring boot and spring data using mongo db
Java and services code lab spring boot and spring data using mongo db
 
Java and services code lab spring boot and spring data using mongo db
Java and services code lab spring boot and spring data using mongo dbJava and services code lab spring boot and spring data using mongo db
Java and services code lab spring boot and spring data using mongo db
 
Spring Data in 10 minutes
Spring Data in 10 minutesSpring Data in 10 minutes
Spring Data in 10 minutes
 
Jpa with spring data
Jpa with spring dataJpa with spring data
Jpa with spring data
 
Data Access 2.0? Please welcome, Spring Data!
Data Access 2.0? Please welcome, Spring Data!Data Access 2.0? Please welcome, Spring Data!
Data Access 2.0? Please welcome, Spring Data!
 
JPQL/ JPA Activity 1
JPQL/ JPA Activity 1JPQL/ JPA Activity 1
JPQL/ JPA Activity 1
 
Web Services Part 2
Web Services Part 2Web Services Part 2
Web Services Part 2
 
15 jpaql
15 jpaql15 jpaql
15 jpaql
 
JPQL/ JPA Activity 2
JPQL/ JPA Activity 2JPQL/ JPA Activity 2
JPQL/ JPA Activity 2
 
Patni Hibernate
Patni   HibernatePatni   Hibernate
Patni Hibernate
 
Ejb5
Ejb5Ejb5
Ejb5
 
JPQL/ JPA Activity 3
JPQL/ JPA  Activity 3JPQL/ JPA  Activity 3
JPQL/ JPA Activity 3
 
15 jpa
15 jpa15 jpa
15 jpa
 
Working with jpa
Working with jpaWorking with jpa
Working with jpa
 

Similaire à Easy data-with-spring-data-jpa

Java Technology
Java TechnologyJava Technology
Java Technology
ifnu bima
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
intelliyole
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
Aren Zomorodian
 

Similaire à Easy data-with-spring-data-jpa (20)

Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming Techniques
 
New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)
 
Java Technology
Java TechnologyJava Technology
Java Technology
 
Spring data requery
Spring data requerySpring data requery
Spring data requery
 
Naver_alternative_to_jpa
Naver_alternative_to_jpaNaver_alternative_to_jpa
Naver_alternative_to_jpa
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
 
Alternatives of JPA/Hibernate
Alternatives of JPA/HibernateAlternatives of JPA/Hibernate
Alternatives of JPA/Hibernate
 
Annotation processing and code gen
Annotation processing and code genAnnotation processing and code gen
Annotation processing and code gen
 
Domain-Driven Design with SeedStack
Domain-Driven Design with SeedStackDomain-Driven Design with SeedStack
Domain-Driven Design with SeedStack
 
JakartaData-JCon.pptx
JakartaData-JCon.pptxJakartaData-JCon.pptx
JakartaData-JCon.pptx
 
Green dao
Green daoGreen dao
Green dao
 
NoSQL Endgame Percona Live Online 2020
NoSQL Endgame Percona Live Online 2020NoSQL Endgame Percona Live Online 2020
NoSQL Endgame Percona Live Online 2020
 
Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Prototype Js
Prototype JsPrototype Js
Prototype Js
 
Object Graph Mapping with Spring Data Neo4j 3 - Nicki Watt & Michael Hunger @...
Object Graph Mapping with Spring Data Neo4j 3 - Nicki Watt & Michael Hunger @...Object Graph Mapping with Spring Data Neo4j 3 - Nicki Watt & Michael Hunger @...
Object Graph Mapping with Spring Data Neo4j 3 - Nicki Watt & Michael Hunger @...
 
Requery overview
Requery overviewRequery overview
Requery overview
 
ADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo
ADO.NET Entity Framework by Jose A. Blakeley and Michael PizzoADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo
ADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
 
NoSQL Endgame DevoxxUA Conference 2020
NoSQL Endgame DevoxxUA Conference 2020NoSQL Endgame DevoxxUA Conference 2020
NoSQL Endgame DevoxxUA Conference 2020
 

Dernier

Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 

Dernier (20)

%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security Program
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 

Easy data-with-spring-data-jpa

  • 1. Easy Data with Spring-Data JPA Miya W. Longwe, Tech Lead, Staples Inc. January 07, 2014 Java Meetup Group, Cambridge, MA , USA
  • 2. Agenda  Java DB Access Ordeal  Enter Spring-Data  Spring-Data JPA Features  Code Demo  Q and A
  • 3. Java DB Access The Developer’s Holy Pilgrim!
  • 4. Application Domain  Domain driven design has become a ubiquitous approach to tackle complex problem domains and build a rich object model.  Implementing a data access layer of an application has been cumbersome for quite a while.  Too much boilerplate code has to be written.  Code to execute simple queries as well as perform pagination, auditing, etc
  • 5. Java DB Access – Accessor Interface public interface CustomerService { Customer findById(Long id); Customer save(Customer customer); List<Customer> findAll(); List<Customer> findAll(int page, int pageSize); ... }
  • 6. Java DB Access – The Boilerplate Code /** * Plain JPA implementation of {@link CustomerService}. * * @author Miya W Longwe */ @Repository @Transactional(readOnly = true) public class CustomerServiceImpl implements CustomerService { @PersistenceContext private EntityManager em; @Override public Customer findById(Long id) { return em.find(Customer.class, id); } @Override public List<Customer> findAll() { return em.createQuery("select c from Customer c", Customer.class).getResultList(); } …… }
  • 7. Java DB Access – The Story ● JPA handles mechanics of ORM ● The catch: – You are responsible for accessor boilerplate code ● Using direct JDBC? – More boilerplate code (think DAO layer) ● What about Spring support? – Makes things better (JdbcTemplate) – Spring-Data eases the pain further
  • 9. Spring-Data  Uses the Repository abstraction for data access  Automation of data access boilerplate code  Reduces level of efforts for accessor code  Support for multiple data stores including– JPA– Key-Value, column, document, graph data stores(Redis, Mongo, Neo4j, HBase)– Hadoop / HDFS – Others
  • 10. Spring-Data JPA Workflow  Define an Entity Class  Define a Repository interface with data accessor methods  Then see you gator!
  • 11. Define Your Entity /** * An entity class which contains the information of a single person. * @author Miya W. Longwe */ @Entity @Table(name = "persons") public class Person { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(name = "creation_time", nullable = false) private Date creationTime; @Column(name = "first_name", nullable = false) private String firstName; @Column(name = "last_name", nullable = false) private String lastName; @Column(name = "modification_time", nullable = false) private Date modificationTime; ...}
  • 12. Define The Repository Interface  You provide a Java interface  – Attach an entity type along with key type  – CRUD/data accessor method signatures  Spring-Data can automatically derive proper JPQL  In simpler cases, no additional code required  Queries are derived from method signatures
  • 13. Repository Interface * Specifies methods used to obtain and modify person related information * which is stored in the database. * @author Miya W. Longwe */ public interface PersonRepository extends JpaRepository<Person, Long> { }
  • 14. No More Boilerplate Code  It goes away (sort of) *  Spring-Data framework derives and attaches JPQL (or specified query) at load-time
  • 16. Provided Repositories  Spring-Data JPA provides two repositories  CrudRepository – Long list of standard CRUD operations provided – findOne(), findAll(), save(), delete(), exists(), etc  PagingAndSortingRepository – Derived from CrudRepository – Provides paginated repository access methods
  • 17. Configure Spring Framework  Specify your repository locations for scanning  Spring will create proxy instances for repositories <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http:/www.springframework.org/schema/beans" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd"> <mvc:resources mapping="/static/**" location="/static/"/> <mvc:default-servlet-handler/> <!-- Configures Spring Data JPA and sets the base package of my DAOs. --> <jpa:repositories base-package="com.meetup.easydata.spring.datajpa.repository"/> </beans>
  • 18. Spring-Data Query Generation  Derived from method signatures  Parses method names for attributes and keywords  Uses method parameters as query params public interface UserRepository extends CrudRepository<User, Long> { List<Customer> findByEmailAddressAndLastname(String emailAddress, String lastname); } Select c from Customer where c.emailAddress = ?1 and c.lastName = ?2
  • 19. Spring-Data Method Name-to-JPQL Mapping Method Name Generated JPQL findByXxxAndYyy(aaa, bbb) ... where t.xxx = ?1 and t.yyy = ?2 findByXxxOrYyy(aaa, bbb) ... where t.xxx = ?1 or t.yyy = ?2 findByXxxStartingWith(a aa) ('%' appended to param value) findByXxxNot(aaa) ... where t.xxx <> ?1 findByXxxIn(Collection< E>aaa) ...where t.xxx in ?1 ---and many more!
  • 20. Spring-Data Further Property Parsing Features -Traversal can reach into nested properties -Will do best effort using camelCase -You can delineate properties using “_” } @Entity public class User <Long> { private ZiCode zicode; --} } public interface UserRepository extends CrudRepository<User, Long>{ ... User findByAddress_ZipCode(ZipCode zipCode);
  • 21. @Query – Use Your Own Query • You don't like the derived query or want to do something fancier? ● Use @Query notation to provide your own ● Support both JPQL or native SQL ● Still provides automatic proxy implementation public interface UserRepository extends CrudRepository<User, Long>{ ... @Query("select u from User u where u.firstname = ?1") List<User> findByFirstname(String firstname); @Query(value="SELECT FROM USERS WHERE EMAIL_ADDRESS = ?1" nativeQuery=true) User findByEmailAddress(String email); ...
  • 22. @Query – Named Params • Spring-Data JPA will use position for parameter binding • You can also use named params instead interface UserRepository extends CrudRepository<User, Long>{ ... @Query("select u from User u where u.firstname = :name or u.lastname = :name") List<User> findByFirstnameOrLastname(@Param("name") String name); ... }
  • 23. Result Pagination • Seamlessly provides support for result set pagination via Pageable Interface • Define repository method with Pageable • Call method with PageRequest class (or define your own) public interface ProductRepository extends CrudRepository<User, Long>{ ... Page<Product> findAll(Pageable pageable); ... } class ProductService { Pageable pageable = new PageRequest(1, 20); Page<Product> page = repository.findByDescriptionContaining(pageable); }
  • 24. Custom Repositories • When Spring-Data JPA derived queries are not • enough or you need additional logic • Provide your own repository implementation • A bean that lives in Spring Context interface UserRepositoryCustom { List<User> myCustomBatchOperation(); } class UserRepositoryImpl implements UserRepositoryCustom { @PersistenceContext private EntityManager em; public List<User> myCustomBatchOperation() { CriteriaQuery<User> criteriaQuery = em.getCriteriaBuilder().createQuery(User.class); return em.createQuery(criteriaQuery).getResultList(); } }
  • 25. Transaction Support • Repository classes are transactional by default • Reads are made readOnly • Other methods are @Transactional by default • Ability to override by providing your own @Transactional demarcation public interface UserRepository extends CrudRepository<User, Long>{ ... @Transactional(timeout=10) @Modifying @Query("update User u set u.firstname = ?1 where u.lastname = ?2") User fixFirstNameByLastName(String firstname, String lastname); ... }