SlideShare a Scribd company logo
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

More Related Content

PPTX
Hibernate ppt
PDF
Spring Data JPA
PPTX
Spring data jpa
PPT
Java Persistence API (JPA) Step By Step
PDF
Spring Data JPA from 0-100 in 60 minutes
PPT
Spring Core
PDF
Hands-On Java web passando por Servlets, JSP, JSTL, JDBC, Hibernate, DAO, MV...
PDF
Spring Framework - Core
Hibernate ppt
Spring Data JPA
Spring data jpa
Java Persistence API (JPA) Step By Step
Spring Data JPA from 0-100 in 60 minutes
Spring Core
Hands-On Java web passando por Servlets, JSP, JSTL, JDBC, Hibernate, DAO, MV...
Spring Framework - Core

What's hot (20)

PDF
Hibernate Presentation
PDF
Spring Framework - AOP
PPTX
Hibernate in Action
PPTX
Getting started with entity framework
PPTX
Introduction to Spring Boot
PPT
ADO.NET Entity Framework
PPTX
Introduction à spring boot
PPTX
ASP.NET Web API
PPTX
Spring Security 5
PPT
Spring Boot in Action
PDF
Exploiting Deserialization Vulnerabilities in Java
PPT
Advanced Javascript
PDF
jQuery - Chapter 3 - Effects
PPTX
Enterprise java unit-2_chapter-2
PPT
Java collections concept
PPTX
Spring boot Introduction
PPTX
PPS
Java Hibernate Programming with Architecture Diagram and Example
PPTX
Ch07 使用 JSTL
PPTX
Enterprise java unit-2_chapter-1
Hibernate Presentation
Spring Framework - AOP
Hibernate in Action
Getting started with entity framework
Introduction to Spring Boot
ADO.NET Entity Framework
Introduction à spring boot
ASP.NET Web API
Spring Security 5
Spring Boot in Action
Exploiting Deserialization Vulnerabilities in Java
Advanced Javascript
jQuery - Chapter 3 - Effects
Enterprise java unit-2_chapter-2
Java collections concept
Spring boot Introduction
Java Hibernate Programming with Architecture Diagram and Example
Ch07 使用 JSTL
Enterprise java unit-2_chapter-1
Ad

Viewers also liked (20)

PPTX
JDBC - JPA - Spring Data
PPTX
Spring Data - Intro (Odessa Java TechTalks)
PDF
Spring Data Jpa
PDF
An introduction into Spring Data
PPT
Spring + JPA + DAO Step by Step
PDF
Spring Data Jpa
PPT
Java Persistence API (JPA) - A Brief Overview
PPTX
Java and services code lab spring boot and spring data using mongo db
PPTX
Java and services code lab spring boot and spring data using mongo db
ODP
Spring Data in 10 minutes
PDF
Jpa with spring data
PDF
Data Access 2.0? Please welcome, Spring Data!
PDF
JPQL/ JPA Activity 1
 
PPT
Web Services Part 2
PPT
15 jpaql
PDF
JPQL/ JPA Activity 2
 
PPT
Patni Hibernate
PPT
PDF
JPQL/ JPA Activity 3
 
PPT
JDBC - JPA - Spring Data
Spring Data - Intro (Odessa Java TechTalks)
Spring Data Jpa
An introduction into Spring Data
Spring + JPA + DAO Step by Step
Spring Data Jpa
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 db
Spring Data in 10 minutes
Jpa with spring data
Data Access 2.0? Please welcome, Spring Data!
JPQL/ JPA Activity 1
 
Web Services Part 2
15 jpaql
JPQL/ JPA Activity 2
 
Patni Hibernate
JPQL/ JPA Activity 3
 
Ad

Similar to Easy data-with-spring-data-jpa (20)

PDF
springdatajpa-up.pdf
PPTX
Spring Data JPA in detail with spring boot
PPTX
Spring Data JPA USE FOR CREATING DATA JPA
ODP
Polyglot persistence with Spring Data
PDF
Spring Data JPA
PPT
YDP_API&MS_UNIT_hiii detail notes to understand api.ppt
PPT
YDP_API&MS_UNIT_IIIii8iiiiiiiii8iiii.ppt
PDF
Data access 2.0? Please welcome: Spring Data!
PDF
Spring Boot Tutorial Part 2 (JPA&Hibernate) .pdf
PPTX
No Sql in Enterprise Java Applications
PPTX
Александр Третьяков: "Spring Data JPA and MongoDB"
PDF
A general introduction to Spring Data / Neo4J
ODP
Data repositories
PPT
Spring data presentation
PDF
springdatajpatwjug-120527215242-phpapp02.pdf
PDF
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
PDF
Under the Hood of Reactive Data Access (1/2)
PDF
Spring data requery
PPT
ORM Concepts and JPA 2.0 Specifications
DOCX
Mastering Spring JPA & Profiles: Practical Guide with Real Data Differences! 🚀
springdatajpa-up.pdf
Spring Data JPA in detail with spring boot
Spring Data JPA USE FOR CREATING DATA JPA
Polyglot persistence with Spring Data
Spring Data JPA
YDP_API&MS_UNIT_hiii detail notes to understand api.ppt
YDP_API&MS_UNIT_IIIii8iiiiiiiii8iiii.ppt
Data access 2.0? Please welcome: Spring Data!
Spring Boot Tutorial Part 2 (JPA&Hibernate) .pdf
No Sql in Enterprise Java Applications
Александр Третьяков: "Spring Data JPA and MongoDB"
A general introduction to Spring Data / Neo4J
Data repositories
Spring data presentation
springdatajpatwjug-120527215242-phpapp02.pdf
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
Under the Hood of Reactive Data Access (1/2)
Spring data requery
ORM Concepts and JPA 2.0 Specifications
Mastering Spring JPA & Profiles: Practical Guide with Real Data Differences! 🚀

Recently uploaded (20)

PPTX
Odoo POS Development Services by CandidRoot Solutions
PPTX
ai tools demonstartion for schools and inter college
PDF
AI in Product Development-omnex systems
PDF
System and Network Administraation Chapter 3
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
How Creative Agencies Leverage Project Management Software.pdf
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PPTX
Introduction to Artificial Intelligence
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PPTX
history of c programming in notes for students .pptx
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Odoo POS Development Services by CandidRoot Solutions
ai tools demonstartion for schools and inter college
AI in Product Development-omnex systems
System and Network Administraation Chapter 3
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
How Creative Agencies Leverage Project Management Software.pdf
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Design an Analysis of Algorithms I-SECS-1021-03
VVF-Customer-Presentation2025-Ver1.9.pptx
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Introduction to Artificial Intelligence
How to Choose the Right IT Partner for Your Business in Malaysia
wealthsignaloriginal-com-DS-text-... (1).pdf
Operating system designcfffgfgggggggvggggggggg
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Odoo Companies in India – Driving Business Transformation.pdf
history of c programming in notes for students .pptx
Internet Downloader Manager (IDM) Crack 6.42 Build 41

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); ... }