SlideShare a Scribd company logo
Spring Data JPA
               CT Yeh @TWJUG 2012/05/26




12年5月28日星期⼀一
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                                                                   @Entity
 public class TodoList {                                                   public class Tag {
 	    @Id                                                                  	    @Id
 	    @GeneratedValue(strategy = GenerationType.AUTO)                      	    @GeneratedValue(strategy = GenerationType.AUTO)
 	    private Long id;                                                     	    private Long id;
                                                                           	
 	   private String category;                                              	    @ManyToMany
                                                                           	    private List<Todo> todos;
 // … methods omitted                                                      	
 }                                                                         	    private String name;

            @Entity                                                        // … methods omitted
            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
            }

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.
                public interface TodoRepository extends JpaRepository<Todo, Long> { … }




         2.    Declare query methods on the repository interface.
                List<Todo> findByTodoList(TodoList todoList);



         3.    Setup Spring configuration.       <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>

         4.    Get the repository instance injected and use it.

                 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
                   <jpa:repositories base-package="com.twjug.repositories"
                    query-lookup-strategy="create-if-not-found"/>




               • create
               • use-declared-query
               • 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




                    You can...

                    List<Person> findByAddressZipCode(ZipCode zipCode);




                    Better way

                    List<Person> findByAddress_ZipCode(ZipCode zipCode);




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
               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.


               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.




                  Spring Data JPA Specification API

                  public interface Specification<T> {
                    Predicate toPredicate(Root<T> root, CriteriaQuery<?> query,
                              CriteriaBuilder builder);
                  }




                 Then, you can use one Repository method for all kind of queries which defined by Specification

                  List<T> readAll(Specification<T> spec);



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 ),

   JPA Criteria API                 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(

      Querydsl                    men.gender.eq(Gender.MALE),
                                  men.relationshipStatus.eq(RelationshipStatus.SINGLE),
                                  women.gender.eq(Gender.FEMALE),
                                  women.relationshipStatus.eq(RelationshipStatus.SINGLE));
                                ....
                            }
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日星期⼀一
Ad

More Related Content

What's hot (20)

Spring Core
Spring CoreSpring Core
Spring Core
Pushan Bhattacharya
 
Spring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesSpring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutes
VMware Tanzu
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
Dzmitry Naskou
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
07.pallav
 
Spring Boot
Spring BootSpring Boot
Spring Boot
Jiayun Zhou
 
Spring boot jpa
Spring boot jpaSpring boot jpa
Spring boot jpa
Hamid Ghorbani
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
Naphachara Rattanawilai
 
Spring Boot
Spring BootSpring Boot
Spring Boot
koppenolski
 
Spring boot
Spring bootSpring boot
Spring boot
sdeeg
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
NexThoughts Technologies
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
guest11106b
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
elliando dias
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
Jakub Kubrynski
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
Ganesh Samarthyam
 
Spring boot
Spring bootSpring boot
Spring boot
Pradeep Shanmugam
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
Purbarun Chakrabarti
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring Data
Arturs Drozdovs
 
Deep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UKDeep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UK
José Paumard
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Scott Leberknight
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
Rohit Verma
 

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
Staples
 
An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring Data
Oliver Gierke
 
Spring Data - Intro (Odessa Java TechTalks)
Spring Data - Intro (Odessa Java TechTalks)Spring Data - Intro (Odessa Java TechTalks)
Spring Data - Intro (Odessa Java TechTalks)
Igor Anishchenko
 
FinelyMe-JustFit Intro
FinelyMe-JustFit IntroFinelyMe-JustFit Intro
FinelyMe-JustFit Intro
Cheng Ta Yeh
 
Spring Transaction
Spring TransactionSpring Transaction
Spring Transaction
patinijava
 
Spring Data Jpa
Spring Data JpaSpring Data Jpa
Spring Data Jpa
Ivan Queiroz
 
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
 
Spring Data Jpa
Spring Data JpaSpring Data Jpa
Spring Data Jpa
Ivan Queiroz
 
Hibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesHibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance Techniques
Brett Meyer
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
ecosio GmbH
 
ORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate Overview
Brett Meyer
 
JPA Best Practices
JPA Best PracticesJPA Best Practices
JPA Best Practices
Carol McDonald
 
Spring Data in 10 minutes
Spring Data in 10 minutesSpring Data in 10 minutes
Spring Data in 10 minutes
Corneil du Plessis
 
Hibernate教程
Hibernate教程Hibernate教程
Hibernate教程
Shilong Sang
 
Thinking Beyond ORM in JPA
Thinking Beyond ORM in JPAThinking Beyond ORM in JPA
Thinking Beyond ORM in JPA
Patrycja Wegrzynowicz
 
Spring Transaction Management
Spring Transaction ManagementSpring Transaction Management
Spring Transaction Management
Ye Win
 
Effective Spring Transaction Management
Effective Spring Transaction ManagementEffective Spring Transaction Management
Effective Spring Transaction Management
UMA MAHESWARI
 
Spring transaction part4
Spring transaction   part4Spring transaction   part4
Spring transaction part4
Santosh Kumar Kar
 
Integrate Spring MVC with RequireJS & Backbone.js & Spring Data JPA
Integrate Spring MVC with RequireJS & Backbone.js & Spring Data JPAIntegrate Spring MVC with RequireJS & Backbone.js & Spring Data JPA
Integrate Spring MVC with RequireJS & Backbone.js & Spring Data JPA
Cheng Ta Yeh
 
Spring Framework - Data Access
Spring Framework - Data AccessSpring Framework - Data Access
Spring Framework - Data Access
Dzmitry Naskou
 
Easy data-with-spring-data-jpa
Easy data-with-spring-data-jpaEasy data-with-spring-data-jpa
Easy data-with-spring-data-jpa
Staples
 
An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring Data
Oliver Gierke
 
Spring Data - Intro (Odessa Java TechTalks)
Spring Data - Intro (Odessa Java TechTalks)Spring Data - Intro (Odessa Java TechTalks)
Spring Data - Intro (Odessa Java TechTalks)
Igor Anishchenko
 
FinelyMe-JustFit Intro
FinelyMe-JustFit IntroFinelyMe-JustFit Intro
FinelyMe-JustFit Intro
Cheng Ta Yeh
 
Spring Transaction
Spring TransactionSpring Transaction
Spring Transaction
patinijava
 
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
 
Hibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesHibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance Techniques
Brett Meyer
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
ecosio GmbH
 
ORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate Overview
Brett Meyer
 
Spring Transaction Management
Spring Transaction ManagementSpring Transaction Management
Spring Transaction Management
Ye Win
 
Effective Spring Transaction Management
Effective Spring Transaction ManagementEffective Spring Transaction Management
Effective Spring Transaction Management
UMA MAHESWARI
 
Integrate Spring MVC with RequireJS & Backbone.js & Spring Data JPA
Integrate Spring MVC with RequireJS & Backbone.js & Spring Data JPAIntegrate Spring MVC with RequireJS & Backbone.js & Spring Data JPA
Integrate Spring MVC with RequireJS & Backbone.js & Spring Data JPA
Cheng Ta Yeh
 
Spring Framework - Data Access
Spring Framework - Data AccessSpring Framework - Data Access
Spring Framework - Data Access
Dzmitry Naskou
 
Ad

Similar to Spring Data JPA (20)

springdatajpatwjug-120527215242-phpapp02.pdf
springdatajpatwjug-120527215242-phpapp02.pdfspringdatajpatwjug-120527215242-phpapp02.pdf
springdatajpatwjug-120527215242-phpapp02.pdf
ssuser0562f1
 
NoSQL Endgame Percona Live Online 2020
NoSQL Endgame Percona Live Online 2020NoSQL Endgame Percona Live Online 2020
NoSQL Endgame Percona Live Online 2020
Thodoris Bais
 
NOSQL part of the SpringOne 2GX 2010 keynote
NOSQL part of the SpringOne 2GX 2010 keynoteNOSQL part of the SpringOne 2GX 2010 keynote
NOSQL part of the SpringOne 2GX 2010 keynote
Emil Eifrem
 
NoSQL Endgame JCON Conference 2020
NoSQL Endgame JCON Conference 2020NoSQL Endgame JCON Conference 2020
NoSQL Endgame JCON Conference 2020
Thodoris Bais
 
20160523 hibernate persistence_framework_and_orm
20160523 hibernate persistence_framework_and_orm20160523 hibernate persistence_framework_and_orm
20160523 hibernate persistence_framework_and_orm
Kenan Sevindik
 
Thomas risberg mongosv-2012-spring-data-cloud-foundry
Thomas risberg mongosv-2012-spring-data-cloud-foundryThomas risberg mongosv-2012-spring-data-cloud-foundry
Thomas risberg mongosv-2012-spring-data-cloud-foundry
trisberg
 
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 @...
Neo4j
 
Green dao 3.0
Green dao 3.0Green dao 3.0
Green dao 3.0
彥彬 洪
 
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
IMC Institute
 
Spring data
Spring dataSpring data
Spring data
명철 강
 
groovy rules
groovy rulesgroovy rules
groovy rules
Paul King
 
WebDSL
WebDSLWebDSL
WebDSL
zefhemel
 
NoSQL Endgame LWJUG 2021
NoSQL Endgame LWJUG 2021NoSQL Endgame LWJUG 2021
NoSQL Endgame LWJUG 2021
Thodoris Bais
 
Android Architecure Components - introduction
Android Architecure Components - introductionAndroid Architecure Components - introduction
Android Architecure Components - introduction
Paulina Szklarska
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
javatwo2011
 
Java 7: Quo vadis?
Java 7: Quo vadis?Java 7: Quo vadis?
Java 7: Quo vadis?
Michal Malohlava
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
Alexey Buzdin
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
C.T.Co
 
Pure Java RAD and Scaffolding Tools Race
Pure Java RAD and Scaffolding Tools RacePure Java RAD and Scaffolding Tools Race
Pure Java RAD and Scaffolding Tools Race
Baruch Sadogursky
 
Kick Start Jpa
Kick Start JpaKick Start Jpa
Kick Start Jpa
Stephan Janssen
 
springdatajpatwjug-120527215242-phpapp02.pdf
springdatajpatwjug-120527215242-phpapp02.pdfspringdatajpatwjug-120527215242-phpapp02.pdf
springdatajpatwjug-120527215242-phpapp02.pdf
ssuser0562f1
 
NoSQL Endgame Percona Live Online 2020
NoSQL Endgame Percona Live Online 2020NoSQL Endgame Percona Live Online 2020
NoSQL Endgame Percona Live Online 2020
Thodoris Bais
 
NOSQL part of the SpringOne 2GX 2010 keynote
NOSQL part of the SpringOne 2GX 2010 keynoteNOSQL part of the SpringOne 2GX 2010 keynote
NOSQL part of the SpringOne 2GX 2010 keynote
Emil Eifrem
 
NoSQL Endgame JCON Conference 2020
NoSQL Endgame JCON Conference 2020NoSQL Endgame JCON Conference 2020
NoSQL Endgame JCON Conference 2020
Thodoris Bais
 
20160523 hibernate persistence_framework_and_orm
20160523 hibernate persistence_framework_and_orm20160523 hibernate persistence_framework_and_orm
20160523 hibernate persistence_framework_and_orm
Kenan Sevindik
 
Thomas risberg mongosv-2012-spring-data-cloud-foundry
Thomas risberg mongosv-2012-spring-data-cloud-foundryThomas risberg mongosv-2012-spring-data-cloud-foundry
Thomas risberg mongosv-2012-spring-data-cloud-foundry
trisberg
 
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 @...
Neo4j
 
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
IMC Institute
 
groovy rules
groovy rulesgroovy rules
groovy rules
Paul King
 
NoSQL Endgame LWJUG 2021
NoSQL Endgame LWJUG 2021NoSQL Endgame LWJUG 2021
NoSQL Endgame LWJUG 2021
Thodoris Bais
 
Android Architecure Components - introduction
Android Architecure Components - introductionAndroid Architecure Components - introduction
Android Architecure Components - introduction
Paulina Szklarska
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
javatwo2011
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
Alexey Buzdin
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
C.T.Co
 
Pure Java RAD and Scaffolding Tools Race
Pure Java RAD and Scaffolding Tools RacePure Java RAD and Scaffolding Tools Race
Pure Java RAD and Scaffolding Tools Race
Baruch Sadogursky
 
Ad

Recently uploaded (20)

What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 

Spring Data JPA

  • 1. Spring Data JPA CT Yeh @TWJUG 2012/05/26 12年5月28日星期⼀一
  • 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 • [email protected] • 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 @Entity public class TodoList { public class Tag { @Id @Id @GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private Long id; private String category; @ManyToMany private List<Todo> todos; // … methods omitted } private String name; @Entity // … methods omitted 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 } 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. public interface TodoRepository extends JpaRepository<Todo, Long> { … } 2. Declare query methods on the repository interface. List<Todo> findByTodoList(TodoList todoList); 3. Setup Spring configuration. <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> 4. Get the repository instance injected and use it. 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 <jpa:repositories base-package="com.twjug.repositories" query-lookup-strategy="create-if-not-found"/> • create • use-declared-query • 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 You can... List<Person> findByAddressZipCode(ZipCode zipCode); Better way List<Person> findByAddress_ZipCode(ZipCode zipCode); 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 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. 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. Spring Data JPA Specification API public interface Specification<T> { Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder); } Then, you can use one Repository method for all kind of queries which defined by Specification List<T> readAll(Specification<T> spec); 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 ), JPA Criteria API 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( Querydsl men.gender.eq(Gender.MALE), men.relationshipStatus.eq(RelationshipStatus.SINGLE), women.gender.eq(Gender.FEMALE), women.relationshipStatus.eq(RelationshipStatus.SINGLE)); .... } 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 [email protected] 12年5月28日星期⼀一