SlideShare ist ein Scribd-Unternehmen logo
1 von 43
Downloaden Sie, um offline zu lesen
實作資料存取
 的抽象化
           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

Weitere ähnliche Inhalte

Was ist angesagt?

Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
Seri Moth
 
Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8
PrinceGuru MS
 
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
Marco Gralike
 

Was ist angesagt? (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
 

Ähnlich wie Spring Data for KSDG 2012/09

Contagion的Ruby/Rails投影片
Contagion的Ruby/Rails投影片Contagion的Ruby/Rails投影片
Contagion的Ruby/Rails投影片
cfc
 
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
Jarod Ferguson
 
エンタープライズ・クラウドと 並列・分散・非同期処理
エンタープライズ・クラウドと 並列・分散・非同期処理エンタープライズ・クラウドと 並列・分散・非同期処理
エンタープライズ・クラウドと 並列・分散・非同期処理
maruyama097
 
Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicate
Kiev ALT.NET
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 
appengine java night #1
appengine java night #1appengine java night #1
appengine java night #1
Shinichi Ogawa
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
Sven Haiges
 

Ähnlich wie 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
 

Kürzlich hochgeladen

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
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
giselly40
 

Kürzlich hochgeladen (20)

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
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
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
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
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
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
 
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
 
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?
 
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
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 

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

Hinweis der Redaktion

  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