SlideShare uma empresa Scribd logo
1 de 33
Baixar para ler offline
Spring Data JPA
CT Yeh @TWJUG 2012/05/26
Outline
• Spring Data Overview
• Let’s get started with plain JPA + Spring
• Refactoring to Spring Data JPA
• Spring Data repository abstraction
• Advanced topics (Specification/
QueryDSL)
• JPA Spring Configurations
12年5月28日星期⼀一
Who Am I
• 葉政達 Cheng-Ta Yeh
• @ctyeh
• ct.yeh@humustech.com
• Co-founder of
• Humus technology (http://www.humustech.com/jento.html)
• Worked for
• Ruckus wireless/BenQ/Everelite/Tainet
• Developer of
• 2011 Android App: GOGOSamba 卡路里天使俱樂部
• Speaker of
• 2008 Google Developer Day
• 2005 JavaOne Tokyo
12年5月28日星期⼀一
Spring Data Overview
• Abstracts away basic data management concepts
• Support for RDB, NoSQL: Graph, Key-Value and Map-
Reduce types.
• Current implementations
• JPA/JDBC
• Hadoop
• GemFire
• REST
• Redis/Riak
• MongoDB
• Neo4j
• Blob (AWS S3, Rackspace, Azure,...)
• Plan for HBase and Cassandra
12年5月28日星期⼀一
Let’s get started
• Plain JPA + Spring
12年5月28日星期⼀一
Overview of the Example
12年5月28日星期⼀一
The Domain Entities
@Entity
public class Todo {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
private TodoList todoList;
@Temporal(TemporalType.DATE)
private Date dueDate;
private Boolean isComplete;
private String title;
@ManyToMany(cascade = { CascadeType.ALL },mappedBy="todos" )
private List<Tag> tags;
// … methods omitted
}
@Entity
public class TodoList {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String category;
// … methods omitted
}
@Entity
public class Tag {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToMany
private List<Todo> todos;
private String name;
// … methods omitted
}
12年5月28日星期⼀一
The DAO
@Repository
public class TodoDAO {!
@PersistenceContext
private EntityManager em;
@Override
@Transactional
public Todo save(Todo todo) {
if (todo.getId() == null) {
em.persist(todo);
return todo;
} else {
return em.merge(todo);
}
}
@Override
public List<Todo> findByTodoList(TodoList todoList) {
TypedQuery query = em.createQuery("select t from Todo a where t.todoList = ?1", Todo.class);
query.setParameter(1, todoList);
return query.getResultList();
}
}
12年5月28日星期⼀一
The Domain Service
@Service
@Transactional(readOnly = true)
class TodoListServiceImpl implements TodoListService {
@Autowired
private TodoDAO todoDAO;
@Override
@Transactional
public Todo save(Todo todo) {
return todoDAO.save(todo);
}
@Override
public List<Todo> findTodos(TodoList todoList) {
return todoDAO.findByTodoList(todoList);
}
}
12年5月28日星期⼀一
Pains
• A lot of code in the persistent framework and DAOs.
1. Create a GenericDAO interface to define generic CRUD.
2. Implement GenericDAO interface to an Abstract
GenericDAO.
3. Define DAO interface for each Domain entity (e.g.,
TodoDao).
4. Implement each DAO interface and extend the Abstract
GenericDAO for specific DAO (e.g., HibernateTodoDao)
• Still some duplicated Code in concrete DAOs.
• JPQL is not type-safe query.
• Pagination need to handle yourself, and integrated from MVC
to persistent layer.
• If hybrid databases (ex, MySQL + MongoDB) are required for
the system, it’s not easy to have similar design concept in
the architecture.
12年5月28日星期⼀一
Refactoring to Spring Data JPA
• Refactoring...... Refactoring......
Refactoring......
12年5月28日星期⼀一
The Repository (DAO)
@Transactional(readOnly = true)
public interface TodoRepository extends JpaRepository<Todo, Long> {
List<Todo> findByTodoList(TodoList todoList);
}
12年5月28日星期⼀一
The Service
@Service
@Transactional(readOnly = true)
class TodoListServiceImpl implements TodoListService {
@Autowired
private TodoRepository repository;
@Override
@Transactional
public Todo save(Todo todo) {
return repository.save(todo);
}
@Override
public List<Todo> findTodos(TodoList todoList) {
return repository.findByTodoList(todoList);
}
}
12年5月28日星期⼀一
Summary of the refactoring
• 4 easy steps
1. Declare an interface extending the specific Repository sub-interface and type it to the domain class it shall handle.
2. Declare query methods on the repository interface.
3. Setup Spring configuration.
4. Get the repository instance injected and use it.
public interface TodoRepository extends JpaRepository<Todo, Long> { … }
List<Todo> findByTodoList(TodoList todoList);
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/data/jpa
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<repositories base-package="com.twjug.repositories" />
</beans>
public class SomeClient {
@Autowired
private TodoRepository repository;
public void doSomething() {
List<Todo> todos = repository.findByTodoList(todoList);
}
12年5月28日星期⼀一
Spring Data Repository Abstraction
• 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>
• Borrow the concept from Domain Driven Design.
12年5月28日星期⼀一
Domain Driven Design
• DDD main approaches
• Entity
• Value Object
• Aggregate
• Repository
12年5月28日星期⼀一
Abstraction Class Diagram
12年5月28日星期⼀一
Query Lookup Strategy
• create
• use-declared-query
• create-if-not-found
<jpa:repositories base-package="com.twjug.repositories"
query-lookup-strategy="create-if-not-found"/>
12年5月28日星期⼀一
Strategy: CREATE
• Split your query methods by prefix and
property names.
12年5月28日星期⼀一
Strategy: CREATE
• Property expressions: traversal
Ex, if you want to traverse: x.address.zipCode
List<Person> findByAddressZipCode(ZipCode zipCode);
List<Person> findByAddress_ZipCode(ZipCode zipCode);
You can...
Better way
12年5月28日星期⼀一
Strategy: USE_DECLARED_QUERY
• @NamedQuery
@Entity
@NamedQuery(name = "User.findByEmailAddress",
query = "select u from User u where u.emailAddress = ?1")
public class User {
}
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByLastname(String lastname);
User findByEmailAddress(String emailAddress);
}
12年5月28日星期⼀一
Strategy: USE_DECLARED_QUERY
• @Query
public interface UserRepository extends JpaRepository<User, Long> {
@Query("select u from User u where u.emailAddress = ?1")
User findByEmailAddress(String emailAddress);
}
From Spring Data JPA 1.1.0, native SQL is allowed to be executed.
Just set nativeQuery flag to true.
But, not support pagination and dynamic sort
12年5月28日星期⼀一
Strategy: USE_DECLARED_QUERY
• @Modify
@Modifying
@Query("update User u set u.firstname = ?1 where u.lastname = ?2")
int setFixedFirstnameFor(String firstname, String lastname);
@Modifying
@Query("update User u set u.firstname = :firstName where u.lastname = :lastName")
int setFixedFirstnameFor(@Param("firstName") String firstname, @Param("lastName") String lastname);
12年5月28日星期⼀一
Advanced Topics
• JPA Specification
• QueryDSL
12年5月28日星期⼀一
Before Using JPA Specification
todoRepository.findUnComplete();
todoRepository.findUnoverdue();
todoRepository.findUncompleteAndUnoverdue();
todoRepository.findOOOXXXX(zz);
……
……
12年5月28日星期⼀一
DDD: The Specification
public interface Specification<T> {
Predicate toPredicate(Root<T> root, CriteriaQuery<?> query,
CriteriaBuilder builder);
}
List<T> readAll(Specification<T> spec);
Spring Data JPA Specification API
Then, you can use one Repository method for all kind of queries which defined by Specification
Solution: Create explicit predicate-like Value Objects for specialized purposes. A Specification is a
predicate that determines if an object does or does not satisfy some criteria.
Problem: Business rules often do not fit the responsibility of any of the obvious Entities or Value
Objects, and their variety and combinations can overwhelm the basic meaning of the domain
object. But moving the rules out of the domain layer is even worse, since the domain code no
longer expresses the model.
12年5月28日星期⼀一
Examples for JPA Specification
• Code
• JPA Metamodel generation with Maven
12年5月28日星期⼀一
Overview of Querydsl
• Querydsl is a framework which enables the
construction of type-safe SQL-like queries for
multiple backends in Java.
• It supports JPA, JDO, SQL, Lucene, Hibernate
Search, Mongodb, Java Collections, Scala。
12年5月28日星期⼀一
Querydsl
• As an alternative to JPA Criteria API
{
CriteriaQuery query = builder.createQuery();
Root<Person> men = query.from( Person.class );
Root<Person> women = query.from( Person.class );
Predicate menRestriction = builder.and(
builder.equal( men.get( Person_.gender ), Gender.MALE ),
builder.equal( men.get( Person_.relationshipStatus ),
RelationshipStatus.SINGLE ));
Predicate womenRestriction = builder.and(
builder.equal( women.get( Person_.gender ), Gender.FEMALE ),
builder.equal( women.get( Person_.relationshipStatus ),
RelationshipStatus.SINGLE ));
query.where( builder.and( menRestriction, womenRestriction ) );
......
}
{
JPAQuery query = new JPAQuery(em);
QPerson men = new QPerson("men");
QPerson women = new QPerson("women");
query.from(men, women).where(
men.gender.eq(Gender.MALE),
men.relationshipStatus.eq(RelationshipStatus.SINGLE),
women.gender.eq(Gender.FEMALE),
women.relationshipStatus.eq(RelationshipStatus.SINGLE));
....
}
JPA Criteria API
Querydsl
12年5月28日星期⼀一
Querydsl Example
• Code
• Maven integration
12年5月28日星期⼀一
Configurations
• Before Spring 3.1, you need
• META-INF/persistence.xml
• orm.xml
• Spring configuration
12年5月28日星期⼀一
Configurations in Spring 3.1
<!-- Activate Spring Data JPA repository support -->
<jpa:repositories base-package="com.humus.domain.repo" />
<!-- Declare a JPA entityManagerFactory -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.humus.domain.entity</value>
</list>
</property>
</bean>
No persistence.xml any more~
12年5月28日星期⼀一
Thank You
Q & A
Humus Technology Wants You
ct.yeh@humustech.com
12年5月28日星期⼀一

Mais conteúdo relacionado

Semelhante a springdatajpatwjug-120527215242-phpapp02.pdf

fdocuments.in_introduction-to-ibatis.ppt
fdocuments.in_introduction-to-ibatis.pptfdocuments.in_introduction-to-ibatis.ppt
fdocuments.in_introduction-to-ibatis.ppt
BruceLee275640
 
Hibernate in XPages
Hibernate in XPagesHibernate in XPages
Hibernate in XPages
Toby Samples
 
5 docker data_etl and visualization_hands_on
5 docker data_etl and visualization_hands_on5 docker data_etl and visualization_hands_on
5 docker data_etl and visualization_hands_on
FEG
 

Semelhante a springdatajpatwjug-120527215242-phpapp02.pdf (20)

Jump Start on Apache Spark 2.2 with Databricks
Jump Start on Apache Spark 2.2 with DatabricksJump Start on Apache Spark 2.2 with Databricks
Jump Start on Apache Spark 2.2 with Databricks
 
Agile Data Engineering - Intro to Data Vault Modeling (2016)
Agile Data Engineering - Intro to Data Vault Modeling (2016)Agile Data Engineering - Intro to Data Vault Modeling (2016)
Agile Data Engineering - Intro to Data Vault Modeling (2016)
 
Agile Data Warehouse Modeling: Introduction to Data Vault Data Modeling
Agile Data Warehouse Modeling: Introduction to Data Vault Data ModelingAgile Data Warehouse Modeling: Introduction to Data Vault Data Modeling
Agile Data Warehouse Modeling: Introduction to Data Vault Data Modeling
 
Migrating on premises workload to azure sql database
Migrating on premises workload to azure sql databaseMigrating on premises workload to azure sql database
Migrating on premises workload to azure sql database
 
Polyglot Database - Linuxcon North America 2016
Polyglot Database - Linuxcon North America 2016Polyglot Database - Linuxcon North America 2016
Polyglot Database - Linuxcon North America 2016
 
QuerySurge Slide Deck for Big Data Testing Webinar
QuerySurge Slide Deck for Big Data Testing WebinarQuerySurge Slide Deck for Big Data Testing Webinar
QuerySurge Slide Deck for Big Data Testing Webinar
 
Secrets of Enterprise Data Mining: SQL Saturday Oregon 201411
Secrets of Enterprise Data Mining: SQL Saturday Oregon 201411Secrets of Enterprise Data Mining: SQL Saturday Oregon 201411
Secrets of Enterprise Data Mining: SQL Saturday Oregon 201411
 
fdocuments.in_introduction-to-ibatis.ppt
fdocuments.in_introduction-to-ibatis.pptfdocuments.in_introduction-to-ibatis.ppt
fdocuments.in_introduction-to-ibatis.ppt
 
Google App Engine
Google App EngineGoogle App Engine
Google App Engine
 
Introduction to NoSQL
Introduction to NoSQLIntroduction to NoSQL
Introduction to NoSQL
 
Stargate, the gateway for some multi-models data API
Stargate, the gateway for some multi-models data APIStargate, the gateway for some multi-models data API
Stargate, the gateway for some multi-models data API
 
Objectivity/DB: A Multipurpose NoSQL Database
Objectivity/DB: A Multipurpose NoSQL DatabaseObjectivity/DB: A Multipurpose NoSQL Database
Objectivity/DB: A Multipurpose NoSQL Database
 
Hibernate in XPages
Hibernate in XPagesHibernate in XPages
Hibernate in XPages
 
Vital AI MetaQL: Queries Across NoSQL, SQL, Sparql, and Spark
Vital AI MetaQL: Queries Across NoSQL, SQL, Sparql, and SparkVital AI MetaQL: Queries Across NoSQL, SQL, Sparql, and Spark
Vital AI MetaQL: Queries Across NoSQL, SQL, Sparql, and Spark
 
BI Environment Technical Analysis
BI Environment Technical AnalysisBI Environment Technical Analysis
BI Environment Technical Analysis
 
Spring Data - Intro (Odessa Java TechTalks)
Spring Data - Intro (Odessa Java TechTalks)Spring Data - Intro (Odessa Java TechTalks)
Spring Data - Intro (Odessa Java TechTalks)
 
Druid Adoption Tips and Tricks
Druid Adoption Tips and TricksDruid Adoption Tips and Tricks
Druid Adoption Tips and Tricks
 
5 docker data_etl and visualization_hands_on
5 docker data_etl and visualization_hands_on5 docker data_etl and visualization_hands_on
5 docker data_etl and visualization_hands_on
 
Spring data presentation
Spring data presentationSpring data presentation
Spring data presentation
 
Introducing U-SQL (SQLPASS 2016)
Introducing U-SQL (SQLPASS 2016)Introducing U-SQL (SQLPASS 2016)
Introducing U-SQL (SQLPASS 2016)
 

Mais de ssuser0562f1 (14)

Алгоритмизация и программирование С/С++
Алгоритмизация и  программирование С/С++Алгоритмизация и  программирование С/С++
Алгоритмизация и программирование С/С++
 
Algorithms and programming lecture in ru
Algorithms and programming lecture in ruAlgorithms and programming lecture in ru
Algorithms and programming lecture in ru
 
Geometry algorithms and formulas calculation
Geometry algorithms and formulas calculationGeometry algorithms and formulas calculation
Geometry algorithms and formulas calculation
 
Algorithms in number theory presentation
Algorithms in number theory presentationAlgorithms in number theory presentation
Algorithms in number theory presentation
 
jpa_nus.pdf
jpa_nus.pdfjpa_nus.pdf
jpa_nus.pdf
 
0808.pdf
0808.pdf0808.pdf
0808.pdf
 
servlets1.pdf
servlets1.pdfservlets1.pdf
servlets1.pdf
 
servlets.pdf
servlets.pdfservlets.pdf
servlets.pdf
 
Курсовая (1).pdf
Курсовая (1).pdfКурсовая (1).pdf
Курсовая (1).pdf
 
springdatajpa-up.pdf
springdatajpa-up.pdfspringdatajpa-up.pdf
springdatajpa-up.pdf
 
08-170327133157.pdf
08-170327133157.pdf08-170327133157.pdf
08-170327133157.pdf
 
waits.pdf
waits.pdfwaits.pdf
waits.pdf
 
waits.pdf
waits.pdfwaits.pdf
waits.pdf
 
geometry.pdf
geometry.pdfgeometry.pdf
geometry.pdf
 

Último

Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 

Último (20)

Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 

springdatajpatwjug-120527215242-phpapp02.pdf

  • 1. Spring Data JPA CT Yeh @TWJUG 2012/05/26
  • 2. Outline • Spring Data Overview • Let’s get started with plain JPA + Spring • Refactoring to Spring Data JPA • Spring Data repository abstraction • Advanced topics (Specification/ QueryDSL) • JPA Spring Configurations 12年5月28日星期⼀一
  • 3. Who Am I • 葉政達 Cheng-Ta Yeh • @ctyeh • ct.yeh@humustech.com • Co-founder of • Humus technology (http://www.humustech.com/jento.html) • Worked for • Ruckus wireless/BenQ/Everelite/Tainet • Developer of • 2011 Android App: GOGOSamba 卡路里天使俱樂部 • Speaker of • 2008 Google Developer Day • 2005 JavaOne Tokyo 12年5月28日星期⼀一
  • 4. Spring Data Overview • Abstracts away basic data management concepts • Support for RDB, NoSQL: Graph, Key-Value and Map- Reduce types. • Current implementations • JPA/JDBC • Hadoop • GemFire • REST • Redis/Riak • MongoDB • Neo4j • Blob (AWS S3, Rackspace, Azure,...) • Plan for HBase and Cassandra 12年5月28日星期⼀一
  • 5. Let’s get started • Plain JPA + Spring 12年5月28日星期⼀一
  • 6. Overview of the Example 12年5月28日星期⼀一
  • 7. The Domain Entities @Entity public class Todo { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @ManyToOne private TodoList todoList; @Temporal(TemporalType.DATE) private Date dueDate; private Boolean isComplete; private String title; @ManyToMany(cascade = { CascadeType.ALL },mappedBy="todos" ) private List<Tag> tags; // … methods omitted } @Entity public class TodoList { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String category; // … methods omitted } @Entity public class Tag { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @ManyToMany private List<Todo> todos; private String name; // … methods omitted } 12年5月28日星期⼀一
  • 8. The DAO @Repository public class TodoDAO {! @PersistenceContext private EntityManager em; @Override @Transactional public Todo save(Todo todo) { if (todo.getId() == null) { em.persist(todo); return todo; } else { return em.merge(todo); } } @Override public List<Todo> findByTodoList(TodoList todoList) { TypedQuery query = em.createQuery("select t from Todo a where t.todoList = ?1", Todo.class); query.setParameter(1, todoList); return query.getResultList(); } } 12年5月28日星期⼀一
  • 9. The Domain Service @Service @Transactional(readOnly = true) class TodoListServiceImpl implements TodoListService { @Autowired private TodoDAO todoDAO; @Override @Transactional public Todo save(Todo todo) { return todoDAO.save(todo); } @Override public List<Todo> findTodos(TodoList todoList) { return todoDAO.findByTodoList(todoList); } } 12年5月28日星期⼀一
  • 10. Pains • A lot of code in the persistent framework and DAOs. 1. Create a GenericDAO interface to define generic CRUD. 2. Implement GenericDAO interface to an Abstract GenericDAO. 3. Define DAO interface for each Domain entity (e.g., TodoDao). 4. Implement each DAO interface and extend the Abstract GenericDAO for specific DAO (e.g., HibernateTodoDao) • Still some duplicated Code in concrete DAOs. • JPQL is not type-safe query. • Pagination need to handle yourself, and integrated from MVC to persistent layer. • If hybrid databases (ex, MySQL + MongoDB) are required for the system, it’s not easy to have similar design concept in the architecture. 12年5月28日星期⼀一
  • 11. Refactoring to Spring Data JPA • Refactoring...... Refactoring...... Refactoring...... 12年5月28日星期⼀一
  • 12. The Repository (DAO) @Transactional(readOnly = true) public interface TodoRepository extends JpaRepository<Todo, Long> { List<Todo> findByTodoList(TodoList todoList); } 12年5月28日星期⼀一
  • 13. The Service @Service @Transactional(readOnly = true) class TodoListServiceImpl implements TodoListService { @Autowired private TodoRepository repository; @Override @Transactional public Todo save(Todo todo) { return repository.save(todo); } @Override public List<Todo> findTodos(TodoList todoList) { return repository.findByTodoList(todoList); } } 12年5月28日星期⼀一
  • 14. Summary of the refactoring • 4 easy steps 1. Declare an interface extending the specific Repository sub-interface and type it to the domain class it shall handle. 2. Declare query methods on the repository interface. 3. Setup Spring configuration. 4. Get the repository instance injected and use it. public interface TodoRepository extends JpaRepository<Todo, Long> { … } List<Todo> findByTodoList(TodoList todoList); <beans:beans xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/data/jpa xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"> <repositories base-package="com.twjug.repositories" /> </beans> public class SomeClient { @Autowired private TodoRepository repository; public void doSomething() { List<Todo> todos = repository.findByTodoList(todoList); } 12年5月28日星期⼀一
  • 15. Spring Data Repository Abstraction • 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> • Borrow the concept from Domain Driven Design. 12年5月28日星期⼀一
  • 16. Domain Driven Design • DDD main approaches • Entity • Value Object • Aggregate • Repository 12年5月28日星期⼀一
  • 18. Query Lookup Strategy • create • use-declared-query • create-if-not-found <jpa:repositories base-package="com.twjug.repositories" query-lookup-strategy="create-if-not-found"/> 12年5月28日星期⼀一
  • 19. Strategy: CREATE • Split your query methods by prefix and property names. 12年5月28日星期⼀一
  • 20. Strategy: CREATE • Property expressions: traversal Ex, if you want to traverse: x.address.zipCode List<Person> findByAddressZipCode(ZipCode zipCode); List<Person> findByAddress_ZipCode(ZipCode zipCode); You can... Better way 12年5月28日星期⼀一
  • 21. Strategy: USE_DECLARED_QUERY • @NamedQuery @Entity @NamedQuery(name = "User.findByEmailAddress", query = "select u from User u where u.emailAddress = ?1") public class User { } public interface UserRepository extends JpaRepository<User, Long> { List<User> findByLastname(String lastname); User findByEmailAddress(String emailAddress); } 12年5月28日星期⼀一
  • 22. Strategy: USE_DECLARED_QUERY • @Query public interface UserRepository extends JpaRepository<User, Long> { @Query("select u from User u where u.emailAddress = ?1") User findByEmailAddress(String emailAddress); } From Spring Data JPA 1.1.0, native SQL is allowed to be executed. Just set nativeQuery flag to true. But, not support pagination and dynamic sort 12年5月28日星期⼀一
  • 23. Strategy: USE_DECLARED_QUERY • @Modify @Modifying @Query("update User u set u.firstname = ?1 where u.lastname = ?2") int setFixedFirstnameFor(String firstname, String lastname); @Modifying @Query("update User u set u.firstname = :firstName where u.lastname = :lastName") int setFixedFirstnameFor(@Param("firstName") String firstname, @Param("lastName") String lastname); 12年5月28日星期⼀一
  • 24. Advanced Topics • JPA Specification • QueryDSL 12年5月28日星期⼀一
  • 25. Before Using JPA Specification todoRepository.findUnComplete(); todoRepository.findUnoverdue(); todoRepository.findUncompleteAndUnoverdue(); todoRepository.findOOOXXXX(zz); …… …… 12年5月28日星期⼀一
  • 26. DDD: The Specification public interface Specification<T> { Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder); } List<T> readAll(Specification<T> spec); Spring Data JPA Specification API Then, you can use one Repository method for all kind of queries which defined by Specification Solution: Create explicit predicate-like Value Objects for specialized purposes. A Specification is a predicate that determines if an object does or does not satisfy some criteria. Problem: Business rules often do not fit the responsibility of any of the obvious Entities or Value Objects, and their variety and combinations can overwhelm the basic meaning of the domain object. But moving the rules out of the domain layer is even worse, since the domain code no longer expresses the model. 12年5月28日星期⼀一
  • 27. Examples for JPA Specification • Code • JPA Metamodel generation with Maven 12年5月28日星期⼀一
  • 28. Overview of Querydsl • Querydsl is a framework which enables the construction of type-safe SQL-like queries for multiple backends in Java. • It supports JPA, JDO, SQL, Lucene, Hibernate Search, Mongodb, Java Collections, Scala。 12年5月28日星期⼀一
  • 29. Querydsl • As an alternative to JPA Criteria API { CriteriaQuery query = builder.createQuery(); Root<Person> men = query.from( Person.class ); Root<Person> women = query.from( Person.class ); Predicate menRestriction = builder.and( builder.equal( men.get( Person_.gender ), Gender.MALE ), builder.equal( men.get( Person_.relationshipStatus ), RelationshipStatus.SINGLE )); Predicate womenRestriction = builder.and( builder.equal( women.get( Person_.gender ), Gender.FEMALE ), builder.equal( women.get( Person_.relationshipStatus ), RelationshipStatus.SINGLE )); query.where( builder.and( menRestriction, womenRestriction ) ); ...... } { JPAQuery query = new JPAQuery(em); QPerson men = new QPerson("men"); QPerson women = new QPerson("women"); query.from(men, women).where( men.gender.eq(Gender.MALE), men.relationshipStatus.eq(RelationshipStatus.SINGLE), women.gender.eq(Gender.FEMALE), women.relationshipStatus.eq(RelationshipStatus.SINGLE)); .... } JPA Criteria API Querydsl 12年5月28日星期⼀一
  • 30. Querydsl Example • Code • Maven integration 12年5月28日星期⼀一
  • 31. Configurations • Before Spring 3.1, you need • META-INF/persistence.xml • orm.xml • Spring configuration 12年5月28日星期⼀一
  • 32. Configurations in Spring 3.1 <!-- Activate Spring Data JPA repository support --> <jpa:repositories base-package="com.humus.domain.repo" /> <!-- Declare a JPA entityManagerFactory --> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <property name="showSql" value="true" /> </bean> </property> <property name="jpaProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop> <prop key="hibernate.hbm2ddl.auto">create</prop> </props> </property> <property name="packagesToScan"> <list> <value>com.humus.domain.entity</value> </list> </property> </bean> No persistence.xml any more~ 12年5月28日星期⼀一
  • 33. Thank You Q & A Humus Technology Wants You ct.yeh@humustech.com 12年5月28日星期⼀一