2011年6月14日 星期二

Play Framework 實驗筆記 1- Data persitence API

首先先從資料物件開始介紹~

關於 Data persitence API,由於考慮到使用雲端服務(ex.GAE)所以找了一下支援的API,發現Siena還不錯,所以先拿來試試看。

目前觀察到Siena 有以下特性:

1. 容易上手,設計也很直覺
2. 同時支援兩大雲端服務
3. 支援目前所有熱門的關聯式資料庫 (採用Apache DdlUtils)

以下是關於Siena Project 的說明
Siena is a single API with many implementations. You can use siena with relational databases, with the Google App Engine's datastore or with Amazon's SimpleDB. There is also an implementation called siena-remote very useful if you want to use the Google App Engine's datastore remotely. Other implmenetations are planned such as: HBase, DBSLayer,...

Siena is Open Source and is released under the Apache License 2.0.

這個範例中會用到兩個資料物件,分別是Member 和 MemberCard,兩者的關係是一個Member會有多張MemberCard(也就是一對多的關係)。下面貼出範例的程式碼供參考:

Member.java
package models;

import java.util.*;
import siena.*;

public class Member extends Model{
     @Id(Generator.AUTO_INCREMENT)
     public Long id;

     @Column("first_name")
     public String firstName;

     @Column("last_name")
     public String lastName;

     @Column("gender")
     public Integer  gender;
     
     @Column("email")
     public String email;
     

     public Member(String firstName, String lastName, int gender, String email) {
         this.firstName = firstName;
         this.lastName = lastName;
         this.gender = gender;
         this.email = email;
     }
     
     public static Query<Member> all() {
         return Model.all(Member.class);
     }
     
     public static List<Member> getall() {
         return all().fetch();
     }
     
     public static Member findById(Long id) {
         return all().filter("id", id).get();
     }
     
     public static Query<MemberCard> findByMember(Long id) {
      Member theMember= all().filter("id", id).get();
      Query<MemberCard> cards = MemberCard.all().filter("member", theMember);
         return cards;
     }
 
}

MemberCard.java
package models;

import java.util.Date;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.OneToMany;

import siena.Column;
import siena.Generator;
import siena.Id;
import siena.Model;
import siena.Query;

public class MemberCard extends Model {

    @Id
    @Column("cardID")
    public String cardID;
    
    @Column("StartDate")
    public Date startDate;
    
    @Column("endDate")
    public Date endDate;
    
    @Column("member")
    public Member member;

    public MemberCard(String cardID) {
        this.cardID = cardID;
    }
  
    public MemberCard(String cardID, Member member) {
        this.cardID = cardID;
        this.member = member;
    }
    
    public static Query<MemberCard> all() {
        return Model.all(MemberCard.class);
    }
    
    public static List<MemberCard> getall() {
        return all().fetch();
    }
    
    public static MemberCard findById(String cardID) {
        return all().filter("cardID", cardID).get();
    }
    
    
}