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 introduction
Spring boot introductionSpring boot introduction
Spring boot introductionRasheed Waraich
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action Alex Movila
 
Easy data-with-spring-data-jpa
Easy data-with-spring-data-jpaEasy data-with-spring-data-jpa
Easy data-with-spring-data-jpaStaples
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API07.pallav
 
Spring Framework - Spring Security
Spring Framework - Spring SecuritySpring Framework - Spring Security
Spring Framework - Spring SecurityDzmitry Naskou
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentationJohn Slick
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate pptAneega
 
Spring framework Controllers and Annotations
Spring framework   Controllers and AnnotationsSpring framework   Controllers and Annotations
Spring framework Controllers and AnnotationsAnuj Singh Rajput
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot IntroductionJeevesh Pandey
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentationguest11106b
 

What's hot (20)

Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
 
Easy data-with-spring-data-jpa
Easy data-with-spring-data-jpaEasy data-with-spring-data-jpa
Easy data-with-spring-data-jpa
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
 
Spring Framework - Spring Security
Spring Framework - Spring SecuritySpring Framework - Spring Security
Spring Framework - Spring Security
 
Spring Core
Spring CoreSpring Core
Spring Core
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentation
 
Xke spring boot
Xke spring bootXke spring boot
Xke spring boot
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Spring framework Controllers and Annotations
Spring framework   Controllers and AnnotationsSpring framework   Controllers and Annotations
Spring framework Controllers and Annotations
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring User Guide
Spring User GuideSpring User Guide
Spring User Guide
 

Viewers also liked

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
 
Spring Framework - Data Access
Spring Framework - Data AccessSpring Framework - Data Access
Spring Framework - Data AccessDzmitry Naskou
 
Spring Data JPA - Repositories done right
Spring Data JPA - Repositories done rightSpring Data JPA - Repositories done right
Spring Data JPA - Repositories done rightOliver Gierke
 

Viewers also liked (20)

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
 
Spring Framework - Data Access
Spring Framework - Data AccessSpring Framework - Data Access
Spring Framework - Data Access
 
Spring Data JPA - Repositories done right
Spring Data JPA - Repositories done rightSpring Data JPA - Repositories done right
Spring Data JPA - Repositories done right
 

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

Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 

Recently uploaded (20)

Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 

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日星期⼀一