SlideShare a Scribd company logo
實作資料存取
 的抽象化
           Cd Chen
 http://www.niceStudio.com.tw/
陳永昇 (Cd Chen)
經歷:
• 乃師實業技術總監
• 恆逸資訊講師
• 聯成電腦講師
• 碩誠資訊研發部經理
專長:
• Unix / Linux 系統管理與開發
• Java / Python / Perl / Objective-C /
C / C++ / PHP / Ruby
• Security / Agile / OOAD
• 全部都是 Java
• 完全不遵守 JSR
• 包含可能影響身
 心健康的內容
世間永遠不會改變的是...



不斷改變的
  需求
給我寫⼀一隻
  “指令模式”
統計訂單金額的程式
public static void main(String[] args){
    System.out.println(“開始統計”);
    List<Order> orders = // ...;
    double sum = 0.0;
    for (Order order : orders) {
        sum += order.getPrice();
    }
    System.out.println(
        “總金額是: ” + sum
    );
}
給我寫⼀一隻
  “指令模式”
  “視窗介面”
統計訂單金額的程式
http://i.mtime.com/3176183/blog/5709802/
內聚 & 耦合
Controller




View                Model
Presentation

Business Logic

 Data Access
單⼀一責任原則
ConsoleUI
 Presentation

 OrderService
Business Logic

OrderRepository
 Data Access
給我寫⼀一隻
  “指令模式”
  “網頁介面”
統計訂單金額的程式
ConsoleUI
   HtmlUI
 Presentation

 OrderService
Business Logic

OrderRepository
 Data Access
針對介面
而非實作
<<use>>
                               Main
                            Presentation



     UserInterface
     +showHint()
+showPrice(price: double)




      <<class>>
  ConsoleUserInterface

     +showHint()
+showPrice(price: double)
public interface UserInterface {
                      void showHint();
                      void showPrice(double price);
                 }

                 public class ConsoleUI
  ConsoleUI          implements UserInterface {

                     public void showHint() {
 Presentation            System.out.println("         ");
                     }

                     public void showPrice(double price) {
   Service               System.out.println("        " + price);
                     }
Business Logic   }


                 public static void main(String[] args) {
 Repository          UserInterface ui = ConsoleUI();
                     ui.showHint();
 Data Access         List<Order> orders = //
                     double price = 0.0;
                                                ...

                     for (Order order : orders)
                         price += order.getPrice();
                     ui.showPrice(price);
                 }
Data Access Layer??
關聯式資料庫             NoSQL        其他

•Native Driver   •MongoDB   •File
•JDBC            •CouchDB   •Web Service
•Hibernate       •Redis     •...
•JPA             •HBase
•...             •...
資料儲存在
  “檔案資料庫”
 “關聯式資料庫”
“NoSQL 資料庫”
     ...
<<use>>
                             Main
                          Data Access




   OrderRepository
 +findAll(): List<Order>




      <<class>>
OrderRepositoryJpaImpl

 +findAll(): List<Order>
public interface OrderRepository {
                      List<Order> findAll();
                 }

                 public class OrderRepositoryJpaImpl
                     implements OrderRepository {
  ConsoleUI
                     public List<Order> findAll() {
 Presentation          //    JPA                       …
                     }
                 }
   Service
                 public static void main(String[] args) {
Business Logic       UserInterface ui = ConsoleUI();
                     ui.showHint();
                     OrderRepository repo =
 Repository              new OrderRepositoryJpaImpl();
                     List<Order> orders = repo.findAll();
 Data Access         double price = 0.0;
                     for (Order order : orders)
                         price += order.getPrice();
                     ui.showPrice(price);
                 }
Spring Data
Spring Data


降低 DAL 耦合
            •減少 DAL 開發
            •簡化 DAL 實作
            •支援 QueryDSL
IoC & AOP
// OrderRepository
public interface OrderRepository {
     List<Order> findAll();
}
                               注入實作細節,
// Main Class                定義於外部的設定中,降
@Autowired
OrderRepository repo;
                             低元件間的耦合,進而提
                                高維護的彈性
@Autowired
UserInterface ui;

public static void main(String[] args) {
    ui.showHint();
    List<Order> orders = repo.findAll();
    double price = 0.0;
    for (Order order : orders)
        price += order.getPrice();
    ui.showPrice(price);
}
Base            Commons
關聯式資料庫          JDBC / JPA
Big Data        Apache Hadoop
Data-Grid       GemFire
HTTP            REST
Document        MongoDB
Graph           Neo4j
Column Stores   HBase
Key-Value       Redis
Repository

                             +save(entity: T): T
                             +findOne(id: ID): T
                             +findAll(): Iterator<T>
                             +count(): Long
                             +delete(entity: T)
     CrudRepository
                             +exists(id: ID): boolean
                             ...

                             +findAll(sort: Sort): Iterator<T>
                             +findAll(pageable: Pageable): Page<T>


PagingAndSortingRepository
Example:
Spring Data JPA
減少 DAL 的開發
public class OrderRepositoryJpaImpl
    implements OrderRepository {

    List<Order> findAll() {
      EntityManager em =
      Query q = em.createQuery(“SELECT o FROM Order o”);
      List<Order> results = new ArrayList<Order>();
      for(Order order : q.getResultList()) {
          results.add(order);
      }
      return results;
    }
}                                       No Spring-Data
public interface OrderJpaRepository
    extends JpaRepository<Order, Long>, OrderRepository {


}



                                       Yes, Spring-Data!!
簡化 DAL 的實作
Method Name
 Keywords
Keyword




findByFFFKKK
    欄位名稱
public interface OrderJpaRepository
    extends JpaRepository<Order, Long>, OrderRepository {

    List<Order> findByDate(Date date);

    List<Order> findByCustomer(Customer customer);

    List<Order> findByCustomerAndDate(Customer c, Date d);

    List<Order> findByCustomer_NameLike(String name);

    List<Order> findByDateBefore(Date theDate);

    List<Order> findByPriceLessThan(double price);

    // ...
}




                             Method Name Keywords
Logic          Keyword
AFTER          After / IsAfter
BEFORE         Before / IsBefore
CONTAINING     Containing / IsContaining / Contains
BETWEEN        Between / IsBetween
ENDING WITH    EndingWith / IsEndingWith / EndsWith
EXISTS         Exists
FALSE          False / IsFalse
GREATER THAN   GreaterThan / IsGreaterThan
GREATER THAN
               GreaterThanEqual / IsGreaterThanEqual
EQUALS

IN             In / IsIn

IS             Is / Equals

IS NOT NULL    NotNull / IsNotNull
Logic              Keyword

IS NULL            Null / IsNull

LESS THAN          LessThan / IsLessThan

LESS THAN EQUALS LessThanEqual / IsLessThanEqual

LIKE               Like / IsLike

NEAR               Near / IsNear

NOT                Not / IsNot

NOT LIKE           NotLike / IsNotLike

REGEX              Regex / MatchesRegex / Maches

STARTING WITH      StartingWith / IsStartingWith / StartsWith

TRUE               True / IsTrue

WITHIN             Within / IsWithin
@Query Annotation
// Order
@Entity
@NamedQuery(
    name=”Order.findByProfitThan100”,
    query=”select o from Order o where price - cost > 100”)
class Order {
  // ...
}

// OrderJpaRepository
public interface OrderJpaRepository
    extends JpaRepository<Order, Long>, OrderRepository {

    List<Order> findByProfitThan100();

    @Query(“select o from Order o where price - cost > 0”)
    List<Order> findByPositiveProfit();

    @Query(“select o from Order o where price > ?1”)
    List<Order> findByPriceGreaterThanArg(double price);

    // ....
}
                                @Query Annotation
Thank you.
http://slidesha.re/Oa2LYT

More Related Content

What's hot

Solid principles
Solid principlesSolid principles
Solid principles
Declan Whelan
 
Solid Software Design Principles
Solid Software Design PrinciplesSolid Software Design Principles
Solid Software Design Principles
Jon Kruger
 
JavaScript Proxy (ES6)
JavaScript Proxy (ES6)JavaScript Proxy (ES6)
JavaScript Proxy (ES6)
Aries Cs
 
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev FedorProgramming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
Fedor Lavrentyev
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Seri Moth
 
Google guava
Google guavaGoogle guava
5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе
DEVTYPE
 
CodingSerbia2014-JavaVSPig
CodingSerbia2014-JavaVSPigCodingSerbia2014-JavaVSPig
CodingSerbia2014-JavaVSPig
Dusan Zamurovic
 
Perforce Object and Record Model
Perforce Object and Record Model  Perforce Object and Record Model
Perforce Object and Record Model
Perforce
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix it
Rafael Dohms
 
Reactive Access to MongoDB from Scala
Reactive Access to MongoDB from ScalaReactive Access to MongoDB from Scala
Reactive Access to MongoDB from Scala
Hermann Hueck
 
ORMLite Android
ORMLite AndroidORMLite Android
ORMLite Android
哲偉 楊
 
Backbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The BrowserBackbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The Browser
Howard Lewis Ship
 
Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8PrinceGuru MS
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
Sandeep Kr. Singh
 
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Kenji Tanaka
 
Boost Your Environment With XMLDB - UKOUG 2008 - Marco Gralike
Boost Your Environment With XMLDB - UKOUG 2008 - Marco GralikeBoost Your Environment With XMLDB - UKOUG 2008 - Marco Gralike
Boost Your Environment With XMLDB - UKOUG 2008 - Marco GralikeMarco Gralike
 
Productaccess m
Productaccess mProductaccess m
Productaccess m
Adil Usman
 
Cfml features modern coding into the box 2018
Cfml features modern coding into the box 2018Cfml features modern coding into the box 2018
Cfml features modern coding into the box 2018
Ortus Solutions, Corp
 

What's hot (20)

Solid principles
Solid principlesSolid principles
Solid principles
 
Solid Software Design Principles
Solid Software Design PrinciplesSolid Software Design Principles
Solid Software Design Principles
 
JavaScript Proxy (ES6)
JavaScript Proxy (ES6)JavaScript Proxy (ES6)
JavaScript Proxy (ES6)
 
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev FedorProgramming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
 
Google guava
Google guavaGoogle guava
Google guava
 
5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе
 
CodingSerbia2014-JavaVSPig
CodingSerbia2014-JavaVSPigCodingSerbia2014-JavaVSPig
CodingSerbia2014-JavaVSPig
 
Perforce Object and Record Model
Perforce Object and Record Model  Perforce Object and Record Model
Perforce Object and Record Model
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix it
 
Reactive Access to MongoDB from Scala
Reactive Access to MongoDB from ScalaReactive Access to MongoDB from Scala
Reactive Access to MongoDB from Scala
 
ORMLite Android
ORMLite AndroidORMLite Android
ORMLite Android
 
Backbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The BrowserBackbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The Browser
 
Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
 
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 
Boost Your Environment With XMLDB - UKOUG 2008 - Marco Gralike
Boost Your Environment With XMLDB - UKOUG 2008 - Marco GralikeBoost Your Environment With XMLDB - UKOUG 2008 - Marco Gralike
Boost Your Environment With XMLDB - UKOUG 2008 - Marco Gralike
 
Productaccess m
Productaccess mProductaccess m
Productaccess m
 
Cfml features modern coding into the box 2018
Cfml features modern coding into the box 2018Cfml features modern coding into the box 2018
Cfml features modern coding into the box 2018
 

Similar to Spring Data for KSDG 2012/09

Contagion的Ruby/Rails投影片
Contagion的Ruby/Rails投影片Contagion的Ruby/Rails投影片
Contagion的Ruby/Rails投影片
cfc
 
JDK Power Tools
JDK Power ToolsJDK Power Tools
JDK Power Tools
Tobias Lindaaker
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
chartjes
 
Performante Java Enterprise Applikationen trotz O/R-Mapping
Performante Java Enterprise Applikationen trotz O/R-MappingPerformante Java Enterprise Applikationen trotz O/R-Mapping
Performante Java Enterprise Applikationen trotz O/R-Mapping
Simon Martinelli
 
.NET Database Toolkit
.NET Database Toolkit.NET Database Toolkit
.NET Database Toolkit
wlscaudill
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsJarod Ferguson
 
エンタープライズ・クラウドと 並列・分散・非同期処理
エンタープライズ・クラウドと 並列・分散・非同期処理エンタープライズ・クラウドと 並列・分散・非同期処理
エンタープライズ・クラウドと 並列・分散・非同期処理maruyama097
 
Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateKiev ALT.NET
 
Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#
Vagif Abilov
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Quebec pdo
Quebec pdoQuebec pdo
Quebec pdo
Valentine Dianov
 
Post Sharp Talk
Post Sharp TalkPost Sharp Talk
Post Sharp Talk
willmation
 
appengine java night #1
appengine java night #1appengine java night #1
appengine java night #1Shinichi Ogawa
 
Construindo APIs de forma produtiva com Spring Boot, Spring Data e Spring MVC
Construindo APIs de forma produtiva com Spring Boot, Spring Data e Spring MVCConstruindo APIs de forma produtiva com Spring Boot, Spring Data e Spring MVC
Construindo APIs de forma produtiva com Spring Boot, Spring Data e Spring MVC
Emmanuel Neri
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on AndroidSven Haiges
 
Nantes Jug - Java 7
Nantes Jug - Java 7Nantes Jug - Java 7
Nantes Jug - Java 7
Sébastien Prunier
 
Building a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to SpaceBuilding a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to Space
Maarten Balliauw
 

Similar to Spring Data for KSDG 2012/09 (20)

Contagion的Ruby/Rails投影片
Contagion的Ruby/Rails投影片Contagion的Ruby/Rails投影片
Contagion的Ruby/Rails投影片
 
JDK Power Tools
JDK Power ToolsJDK Power Tools
JDK Power Tools
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
Performante Java Enterprise Applikationen trotz O/R-Mapping
Performante Java Enterprise Applikationen trotz O/R-MappingPerformante Java Enterprise Applikationen trotz O/R-Mapping
Performante Java Enterprise Applikationen trotz O/R-Mapping
 
.NET Database Toolkit
.NET Database Toolkit.NET Database Toolkit
.NET Database Toolkit
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
 
エンタープライズ・クラウドと 並列・分散・非同期処理
エンタープライズ・クラウドと 並列・分散・非同期処理エンタープライズ・クラウドと 並列・分散・非同期処理
エンタープライズ・クラウドと 並列・分散・非同期処理
 
Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicate
 
Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Quebec pdo
Quebec pdoQuebec pdo
Quebec pdo
 
Post Sharp Talk
Post Sharp TalkPost Sharp Talk
Post Sharp Talk
 
Solr @ Etsy - Apache Lucene Eurocon
Solr @ Etsy - Apache Lucene EuroconSolr @ Etsy - Apache Lucene Eurocon
Solr @ Etsy - Apache Lucene Eurocon
 
appengine java night #1
appengine java night #1appengine java night #1
appengine java night #1
 
Construindo APIs de forma produtiva com Spring Boot, Spring Data e Spring MVC
Construindo APIs de forma produtiva com Spring Boot, Spring Data e Spring MVCConstruindo APIs de forma produtiva com Spring Boot, Spring Data e Spring MVC
Construindo APIs de forma produtiva com Spring Boot, Spring Data e Spring MVC
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
 
Nantes Jug - Java 7
Nantes Jug - Java 7Nantes Jug - Java 7
Nantes Jug - Java 7
 
Building a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to SpaceBuilding a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to Space
 

Recently uploaded

GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Vladimir Iglovikov, Ph.D.
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 

Recently uploaded (20)

GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 

Spring Data for KSDG 2012/09

  • 1. 實作資料存取 的抽象化 Cd Chen http://www.niceStudio.com.tw/
  • 2. 陳永昇 (Cd Chen) 經歷: • 乃師實業技術總監 • 恆逸資訊講師 • 聯成電腦講師 • 碩誠資訊研發部經理 專長: • Unix / Linux 系統管理與開發 • Java / Python / Perl / Objective-C / C / C++ / PHP / Ruby • Security / Agile / OOAD
  • 3. • 全部都是 Java • 完全不遵守 JSR • 包含可能影響身 心健康的內容
  • 6. public static void main(String[] args){ System.out.println(“開始統計”); List<Order> orders = // ...; double sum = 0.0; for (Order order : orders) { sum += order.getPrice(); } System.out.println( “總金額是: ” + sum ); }
  • 7. 給我寫⼀一隻 “指令模式” “視窗介面” 統計訂單金額的程式
  • 13. ConsoleUI Presentation OrderService Business Logic OrderRepository Data Access
  • 14. 給我寫⼀一隻 “指令模式” “網頁介面” 統計訂單金額的程式
  • 15. ConsoleUI HtmlUI Presentation OrderService Business Logic OrderRepository Data Access
  • 17. <<use>> Main Presentation UserInterface +showHint() +showPrice(price: double) <<class>> ConsoleUserInterface +showHint() +showPrice(price: double)
  • 18. public interface UserInterface { void showHint(); void showPrice(double price); } public class ConsoleUI ConsoleUI implements UserInterface { public void showHint() { Presentation System.out.println(" "); } public void showPrice(double price) { Service System.out.println(" " + price); } Business Logic } public static void main(String[] args) { Repository UserInterface ui = ConsoleUI(); ui.showHint(); Data Access List<Order> orders = // double price = 0.0; ... for (Order order : orders) price += order.getPrice(); ui.showPrice(price); }
  • 20. 關聯式資料庫 NoSQL 其他 •Native Driver •MongoDB •File •JDBC •CouchDB •Web Service •Hibernate •Redis •... •JPA •HBase •... •...
  • 21. 資料儲存在 “檔案資料庫” “關聯式資料庫” “NoSQL 資料庫” ...
  • 22. <<use>> Main Data Access OrderRepository +findAll(): List<Order> <<class>> OrderRepositoryJpaImpl +findAll(): List<Order>
  • 23. public interface OrderRepository { List<Order> findAll(); } public class OrderRepositoryJpaImpl implements OrderRepository { ConsoleUI public List<Order> findAll() { Presentation // JPA … } } Service public static void main(String[] args) { Business Logic UserInterface ui = ConsoleUI(); ui.showHint(); OrderRepository repo = Repository new OrderRepositoryJpaImpl(); List<Order> orders = repo.findAll(); Data Access double price = 0.0; for (Order order : orders) price += order.getPrice(); ui.showPrice(price); }
  • 24.
  • 26. Spring Data 降低 DAL 耦合 •減少 DAL 開發 •簡化 DAL 實作 •支援 QueryDSL
  • 27.
  • 29. // OrderRepository public interface OrderRepository { List<Order> findAll(); } 注入實作細節, // Main Class 定義於外部的設定中,降 @Autowired OrderRepository repo; 低元件間的耦合,進而提 高維護的彈性 @Autowired UserInterface ui; public static void main(String[] args) { ui.showHint(); List<Order> orders = repo.findAll(); double price = 0.0; for (Order order : orders) price += order.getPrice(); ui.showPrice(price); }
  • 30. Base Commons 關聯式資料庫 JDBC / JPA Big Data Apache Hadoop Data-Grid GemFire HTTP REST Document MongoDB Graph Neo4j Column Stores HBase Key-Value Redis
  • 31. Repository +save(entity: T): T +findOne(id: ID): T +findAll(): Iterator<T> +count(): Long +delete(entity: T) CrudRepository +exists(id: ID): boolean ... +findAll(sort: Sort): Iterator<T> +findAll(pageable: Pageable): Page<T> PagingAndSortingRepository
  • 34. public class OrderRepositoryJpaImpl implements OrderRepository { List<Order> findAll() { EntityManager em = Query q = em.createQuery(“SELECT o FROM Order o”); List<Order> results = new ArrayList<Order>(); for(Order order : q.getResultList()) { results.add(order); } return results; } } No Spring-Data public interface OrderJpaRepository extends JpaRepository<Order, Long>, OrderRepository { } Yes, Spring-Data!!
  • 37. Keyword findByFFFKKK 欄位名稱
  • 38. public interface OrderJpaRepository extends JpaRepository<Order, Long>, OrderRepository { List<Order> findByDate(Date date); List<Order> findByCustomer(Customer customer); List<Order> findByCustomerAndDate(Customer c, Date d); List<Order> findByCustomer_NameLike(String name); List<Order> findByDateBefore(Date theDate); List<Order> findByPriceLessThan(double price); // ... } Method Name Keywords
  • 39. Logic Keyword AFTER After / IsAfter BEFORE Before / IsBefore CONTAINING Containing / IsContaining / Contains BETWEEN Between / IsBetween ENDING WITH EndingWith / IsEndingWith / EndsWith EXISTS Exists FALSE False / IsFalse GREATER THAN GreaterThan / IsGreaterThan GREATER THAN GreaterThanEqual / IsGreaterThanEqual EQUALS IN In / IsIn IS Is / Equals IS NOT NULL NotNull / IsNotNull
  • 40. Logic Keyword IS NULL Null / IsNull LESS THAN LessThan / IsLessThan LESS THAN EQUALS LessThanEqual / IsLessThanEqual LIKE Like / IsLike NEAR Near / IsNear NOT Not / IsNot NOT LIKE NotLike / IsNotLike REGEX Regex / MatchesRegex / Maches STARTING WITH StartingWith / IsStartingWith / StartsWith TRUE True / IsTrue WITHIN Within / IsWithin
  • 42. // Order @Entity @NamedQuery( name=”Order.findByProfitThan100”, query=”select o from Order o where price - cost > 100”) class Order { // ... } // OrderJpaRepository public interface OrderJpaRepository extends JpaRepository<Order, Long>, OrderRepository { List<Order> findByProfitThan100(); @Query(“select o from Order o where price - cost > 0”) List<Order> findByPositiveProfit(); @Query(“select o from Order o where price > ?1”) List<Order> findByPriceGreaterThanArg(double price); // .... } @Query Annotation

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n