Spring Data for KSDG 2012/09

Post on 14-May-2015

830 views 3 download

description

這是 Cd Chen 在 2012/09 於 KSDG 的技術分享之投影片。

Transcript of Spring Data for KSDG 2012/09

實作資料存取的抽象化

Cd Chenhttp://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

Data Access

Business Logic

Presentation

單⼀一責任原則

Data Access

Business Logic

PresentationConsoleUI

OrderService

OrderRepository

給我寫⼀一隻 “指令模式”“網頁介面”

統計訂單金額的程式

Data Access

Business Logic

PresentationConsoleUIHtmlUI

OrderService

OrderRepository

針對介面而非實作

<<use>>

Presentation

Main

<<class>>ConsoleUserInterface

+showHint()+showPrice(price: double)

UserInterface+showHint()

+showPrice(price: double)

Data Access

Business Logic

Presentation

Repository

Service

ConsoleUI

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

public class ConsoleUI implements UserInterface {

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

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

public static void main(String[] args) { UserInterface ui = ConsoleUI(); ui.showHint(); List<Order> orders = // �... double price = 0.0; for (Order order : orders) price += order.getPrice(); ui.showPrice(price);}

Data Access Layer??

關聯式資料庫 NoSQL 其他

•Native Driver•JDBC•Hibernate•JPA•...

•MongoDB•CouchDB•Redis•HBase•...

•File•Web Service•...

資料儲存在“檔案資料庫”

“關聯式資料庫”“NoSQL 資料庫”

...

<<class>>OrderRepositoryJpaImpl

+findAll(): List<Order>

<<use>>

Data Access

Main

OrderRepository+findAll(): List<Order>

Data Access

Business Logic

Presentation

Service

ConsoleUI

Repository

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

public class OrderRepositoryJpaImpl implements OrderRepository {

public List<Order> findAll() { // � JPA ��������� ��… }}

public static void main(String[] args) { UserInterface ui = ConsoleUI(); ui.showHint(); OrderRepository repo = new OrderRepositoryJpaImpl(); List<Order> orders = repo.findAll(); double price = 0.0; for (Order order : orders) price += order.getPrice(); ui.showPrice(price);}

Spring Data

降低 DAL 耦合

Spring Data

•減少 DAL 開發•簡化 DAL 實作•支援 QueryDSL

IoC & AOP

注入實作細節,定義於外部的設定中,降低元件間的耦合,進而提

高維護的彈性

// OrderRepositorypublic interface OrderRepository { List<Order> findAll();}

// Main Class@AutowiredOrderRepository repo;

@AutowiredUserInterface 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 HadoopData-Grid GemFireHTTP RESTDocument MongoDBGraph Neo4jColumn Stores HBaseKey-Value Redis

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

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

CrudRepository

Repository

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-Datapublic interface OrderJpaRepository extends JpaRepository<Order, Long>, OrderRepository {

}

Yes, Spring-Data!!

簡化 DAL 的實作

Method Name Keywords

findByFFFKKK欄位名稱

Keyword

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 KeywordAFTER After / IsAfterBEFORE Before / IsBeforeCONTAINING Containing / IsContaining / ContainsBETWEEN Between / IsBetweenENDING WITH EndingWith / IsEndingWith / EndsWithEXISTS ExistsFALSE False / IsFalseGREATER THAN GreaterThan / IsGreaterThan

GREATER THAN EQUALS GreaterThanEqual / IsGreaterThanEqual

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 { // ...}

// OrderJpaRepositorypublic 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