SlideShare a Scribd company logo
1 of 33
Download to read offline
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日星期⼀一

More Related Content

What's hot

Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action Alex Movila
 
Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introductionJonathan Holloway
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentationguest11106b
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring BootTrey Howard
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - CoreDzmitry Naskou
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlArjun Thakur
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOPDzmitry Naskou
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootJosué Neis
 
Overview of JPA (Java Persistence API) v2.0
Overview of JPA (Java Persistence API) v2.0Overview of JPA (Java Persistence API) v2.0
Overview of JPA (Java Persistence API) v2.0Bryan Basham
 

What's hot (20)

Spring boot
Spring bootSpring boot
Spring boot
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
 
Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introduction
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Spring boot
Spring bootSpring boot
Spring boot
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
Spring Security 5
Spring Security 5Spring Security 5
Spring Security 5
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
 
Spring Security
Spring SecuritySpring Security
Spring Security
 
Spring User Guide
Spring User GuideSpring User Guide
Spring User Guide
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Spring boot jpa
Spring boot jpaSpring boot jpa
Spring boot jpa
 
Spring annotation
Spring annotationSpring annotation
Spring annotation
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBoot
 
Spring jdbc
Spring jdbcSpring jdbc
Spring jdbc
 
Overview of JPA (Java Persistence API) v2.0
Overview of JPA (Java Persistence API) v2.0Overview of JPA (Java Persistence API) v2.0
Overview of JPA (Java Persistence API) v2.0
 

Viewers also liked

JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring DataArturs Drozdovs
 
Easy data-with-spring-data-jpa
Easy data-with-spring-data-jpaEasy data-with-spring-data-jpa
Easy data-with-spring-data-jpaStaples
 
An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring DataOliver 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 IntroCheng Ta Yeh
 
Spring Transaction
Spring TransactionSpring Transaction
Spring Transactionpatinijava
 
Spring + JPA + DAO Step by Step
Spring + JPA + DAO Step by StepSpring + JPA + DAO Step by Step
Spring + JPA + DAO Step by StepGuo 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 TechniquesBrett 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 examplesecosio GmbH
 
ORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewBrett Meyer
 
Spring Transaction Management
Spring Transaction ManagementSpring Transaction Management
Spring Transaction ManagementYe Win
 
Effective Spring Transaction Management
Effective Spring Transaction ManagementEffective Spring Transaction Management
Effective Spring Transaction ManagementUMA 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 JPACheng Ta Yeh
 

Viewers also liked (20)

JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring Data
 
Easy data-with-spring-data-jpa
Easy data-with-spring-data-jpaEasy data-with-spring-data-jpa
Easy data-with-spring-data-jpa
 
An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring Data
 
Spring Data - Intro (Odessa Java TechTalks)
Spring Data - Intro (Odessa Java TechTalks)Spring Data - Intro (Odessa Java TechTalks)
Spring Data - Intro (Odessa Java TechTalks)
 
FinelyMe-JustFit Intro
FinelyMe-JustFit IntroFinelyMe-JustFit Intro
FinelyMe-JustFit Intro
 
Spring Transaction
Spring TransactionSpring Transaction
Spring Transaction
 
Spring Data Jpa
Spring Data JpaSpring Data Jpa
Spring Data Jpa
 
Spring + JPA + DAO Step by Step
Spring + JPA + DAO Step by StepSpring + JPA + DAO Step by Step
Spring + JPA + DAO Step by Step
 
Spring Data Jpa
Spring Data JpaSpring Data Jpa
Spring Data Jpa
 
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
 
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
 
ORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate Overview
 
JPA Best Practices
JPA Best PracticesJPA Best Practices
JPA Best Practices
 
Spring Data in 10 minutes
Spring Data in 10 minutesSpring Data in 10 minutes
Spring Data in 10 minutes
 
Hibernate教程
Hibernate教程Hibernate教程
Hibernate教程
 
Thinking Beyond ORM in JPA
Thinking Beyond ORM in JPAThinking Beyond ORM in JPA
Thinking Beyond ORM in JPA
 
Spring Transaction Management
Spring Transaction ManagementSpring Transaction Management
Spring Transaction Management
 
Effective Spring Transaction Management
Effective Spring Transaction ManagementEffective Spring Transaction Management
Effective Spring Transaction Management
 
Spring transaction part4
Spring transaction   part4Spring transaction   part4
Spring transaction part4
 
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
 

Similar to Spring Data JPA

springdatajpatwjug-120527215242-phpapp02.pdf
springdatajpatwjug-120527215242-phpapp02.pdfspringdatajpatwjug-120527215242-phpapp02.pdf
springdatajpatwjug-120527215242-phpapp02.pdfssuser0562f1
 
NoSQL Endgame Percona Live Online 2020
NoSQL Endgame Percona Live Online 2020NoSQL Endgame Percona Live Online 2020
NoSQL Endgame Percona Live Online 2020Thodoris 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 keynoteEmil Eifrem
 
NoSQL Endgame JCON Conference 2020
NoSQL Endgame JCON Conference 2020NoSQL Endgame JCON Conference 2020
NoSQL Endgame JCON Conference 2020Thodoris Bais
 
20160523 hibernate persistence_framework_and_orm
20160523 hibernate persistence_framework_and_orm20160523 hibernate persistence_framework_and_orm
20160523 hibernate persistence_framework_and_ormKenan 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-foundrytrisberg
 
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] : DatastoreIMC Institute
 
groovy rules
groovy rulesgroovy rules
groovy rulesPaul King
 
NoSQL Endgame LWJUG 2021
NoSQL Endgame LWJUG 2021NoSQL Endgame LWJUG 2021
NoSQL Endgame LWJUG 2021Thodoris Bais
 
Android Architecure Components - introduction
Android Architecure Components - introductionAndroid Architecure Components - introduction
Android Architecure Components - introductionPaulina Szklarska
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureAlexey Buzdin
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureC.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 RaceBaruch Sadogursky
 

Similar to Spring Data JPA (20)

springdatajpatwjug-120527215242-phpapp02.pdf
springdatajpatwjug-120527215242-phpapp02.pdfspringdatajpatwjug-120527215242-phpapp02.pdf
springdatajpatwjug-120527215242-phpapp02.pdf
 
NoSQL Endgame Percona Live Online 2020
NoSQL Endgame Percona Live Online 2020NoSQL Endgame Percona Live Online 2020
NoSQL Endgame Percona Live Online 2020
 
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
 
NoSQL Endgame JCON Conference 2020
NoSQL Endgame JCON Conference 2020NoSQL Endgame JCON Conference 2020
NoSQL Endgame JCON Conference 2020
 
20160523 hibernate persistence_framework_and_orm
20160523 hibernate persistence_framework_and_orm20160523 hibernate persistence_framework_and_orm
20160523 hibernate persistence_framework_and_orm
 
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
 
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 @...
 
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
 
Spring data
Spring dataSpring data
Spring data
 
groovy rules
groovy rulesgroovy rules
groovy rules
 
WebDSL
WebDSLWebDSL
WebDSL
 
NoSQL Endgame LWJUG 2021
NoSQL Endgame LWJUG 2021NoSQL Endgame LWJUG 2021
NoSQL Endgame LWJUG 2021
 
Android Architecure Components - introduction
Android Architecure Components - introductionAndroid Architecure Components - introduction
Android Architecure Components - introduction
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Java 7: Quo vadis?
Java 7: Quo vadis?Java 7: Quo vadis?
Java 7: Quo vadis?
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
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
 
Kick Start Jpa
Kick Start JpaKick Start Jpa
Kick Start Jpa
 

Recently uploaded

[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 

Recently uploaded (20)

[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 

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 • 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 @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 ct.yeh@humustech.com 12年5月28日星期⼀一