Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android ORM系列之GreenDao最佳實踐

Android ORM系列之GreenDao最佳實踐

編輯:關於Android編程

GreenDAO是一個可以幫助Android開發者快速將Java對象映射到SQLite數據庫的表單中的ORM解決方案,通過使用一個簡單的面向對象API,開發者可以對Java對象進行存儲、更新、刪除和查詢。

GreenDao有兩個項目,一個是生成dao和model的generator的項目,該項目是java項目,一個是用於android的核心jar包。在使用前,我們必須先生成dao和model。

首先加入依賴。

compile 'de.greenrobot:greendao:2.0.0'
compile 'de.greenrobot:greendao-generator:2.0.0'

然後在我們的包名之下新建一個db的包,在db下新建dao和model的包以及一個generator的包,就像下圖。
這裡寫圖片描述

在generatZ喎?/kf/ware/vc/" target="_blank" class="keylink">vcrD8z8KjrNDCvajSu7j2yfqzyWRhb7rNbW9kZWy1xMDgR3JlZW5EYW9HZW5lcmF0b3KjrNTawO/D5rzTyOu0+sLrPC9wPg0KPHByZSBjbGFzcz0="brush:java;"> public class GreenDaoGenerator { public static void main(String[] args) throws Exception { Schema schema = new Schema(1, cn.edu.zafu.greendao.db.model); schema.setDefaultJavaPackageDao(cn.edu.zafu.greendao.db.dao); schema.enableKeepSectionsByDefault(); //schema.enableActiveEntitiesByDefault(); //ActiveRecord addEntity(schema); new DaoGenerator().generateAll(schema, ./app/src/main/java); } private static void addEntity(Schema schema) { Entity person = schema.addEntity(Person); person.addIdProperty().primaryKey(); person.addStringProperty(name); person.addDoubleProperty(height); person.addDoubleProperty(weight); Entity card = schema.addEntity(Card); card.addIdProperty().primaryKey(); card.addStringProperty(num); card.addStringProperty(address); Property idcardPK = person.addLongProperty(cardId).getProperty(); person.addToOne(card, idcardPK); Property personPK = card.addLongProperty(personId).getProperty(); card.addToOne(person,personPK); } }

Schema schema = new Schema(1, “cn.edu.zafu.greendao.db.model”); 代表創建的數據庫的版本號以及默認的java package,如果不修改默認的包名,生成的dao和model都會在該包下,這裡我們修改了dao的包名schema.setDefaultJavaPackageDao(“cn.edu.zafu.greendao.db.dao”);,生成的model中,我們可能需要加入自己的一些信息,但是又不希望下次生成的時候消失,所以可以使用schema.enableKeepSectionsByDefault();,使用後會在model類中有如下這些標示

// KEEP INCLUDES - put your custom includes here
// KEEP INCLUDES END

// KEEP FIELDS - put your custom fields here
// KEEP FIELDS END

 // KEEP METHODS - put your custom methods here
// KEEP METHODS END

你只需將你需要的信息添加到這三個之間,分布代表引入的包,字段,方法。之後重新生成這些信息將會被保留。

schema.enableActiveEntitiesByDefault();代表實體類是否支持active,用過php中yii框架的都應該清楚,實體類可以直接進行crud操作。我們不開啟就好了,如果開啟了的話,實體類將之間支持update, refresh, deleted 等操作。

之後就使用 schema.addEntity()函數增加Entity 對象,即對應的實體類,通過添加屬性方法addProperty系列方法增加字段,最後調用new DaoGenerator().generateAll(schema, “./app/src/main/java”);方法生成dao和model。

生成的步驟也很簡單,在該類上右鍵,點run即可。

這裡寫圖片描述

生成之後控制台就會輸出

這裡寫圖片描述

然後我們編寫一個核心輔助類。用於獲取DaoMaster和DaoSession

public class DbCore {
    private static final String DEFAULT_DB_NAME = default.db;
    private static DaoMaster daoMaster;
    private static DaoSession daoSession;

    private static Context mContext;
    private static String DB_NAME;

    public static void init(Context context) {
        init(context, DEFAULT_DB_NAME);
    }

    public static void init(Context context, String dbName) {
        if (context == null) {
            throw new IllegalArgumentException(context can't be null);
        }
        mContext = context.getApplicationContext();
        DB_NAME = dbName;
    }

    public static DaoMaster getDaoMaster() {
        if (daoMaster == null) {
            DaoMaster.OpenHelper helper = new DaoMaster.DevOpenHelper(mContext, DB_NAME, null);
            daoMaster = new DaoMaster(helper.getWritableDatabase());
        }
        return daoMaster;
    }

    public static DaoSession getDaoSession() {
        if (daoSession == null) {
            if (daoMaster == null) {
                daoMaster = getDaoMaster();
            }
            daoSession = daoMaster.newSession();
        }
        return daoSession;
    }

    public static void enableQueryBuilderLog(){

        QueryBuilder.LOG_SQL = true;
        QueryBuilder.LOG_VALUES = true;
    }
}

接下來就是基礎的泛型Service

 {
    private AbstractDao mDao;


    public BaseService(AbstractDao dao) {
        mDao = dao;
    }


    public void save(T item) {
        mDao.insert(item);
    }

    public void save(T... items) {
        mDao.insertInTx(items);
    }

    public void save(List items) {
        mDao.insertInTx(items);
    }

    public void saveOrUpdate(T item) {
        mDao.insertOrReplace(item);
    }

    public void saveOrUpdate(T... items) {
        mDao.insertOrReplaceInTx(items);
    }

    public void saveOrUpdate(List items) {
        mDao.insertOrReplaceInTx(items);
    }

    public void deleteByKey(K key) {
        mDao.deleteByKey(key);
    }

    public void delete(T item) {
        mDao.delete(item);
    }

    public void delete(T... items) {
        mDao.deleteInTx(items);
    }

    public void delete(List items) {
        mDao.deleteInTx(items);
    }

    public void deleteAll() {
        mDao.deleteAll();
    }


    public void update(T item) {
        mDao.update(item);
    }

    public void update(T... items) {
        mDao.updateInTx(items);
    }

    public void update(List items) {
        mDao.updateInTx(items);
    }

    public  T query(K key) {
        return  mDao.load(key);
    }

    public List queryAll() {
        return mDao.loadAll();
    }

    public List query(String where, String... params) {

        return mDao.queryRaw(where, params);
    }

    public QueryBuilder queryBuilder() {

        return mDao.queryBuilder();
    }

    public long count() {
        return mDao.count();
    }

    public void refresh(T item) {
        mDao.refresh(item);

    }

    public void detach(T item) {
        mDao.detach(item);
    }
}
 data-snippet-id=ext.28cd87bcf7b80ae158ac8a8cb2592b4d data-snippet-saved=false data-csrftoken=X78ashm8-qdtZAdswI6QWL7nrYl61g05iwCQ data-codota-status=done>public class BaseService {
    private AbstractDao mDao;


    public BaseService(AbstractDao dao) {
        mDao = dao;
    }


    public void save(T item) {
        mDao.insert(item);
    }

    public void save(T... items) {
        mDao.insertInTx(items);
    }

    public void save(List items) {
        mDao.insertInTx(items);
    }

    public void saveOrUpdate(T item) {
        mDao.insertOrReplace(item);
    }

    public void saveOrUpdate(T... items) {
        mDao.insertOrReplaceInTx(items);
    }

    public void saveOrUpdate(List items) {
        mDao.insertOrReplaceInTx(items);
    }

    public void deleteByKey(K key) {
        mDao.deleteByKey(key);
    }

    public void delete(T item) {
        mDao.delete(item);
    }

    public void delete(T... items) {
        mDao.deleteInTx(items);
    }

    public void delete(List items) {
        mDao.deleteInTx(items);
    }

    public void deleteAll() {
        mDao.deleteAll();
    }


    public void update(T item) {
        mDao.update(item);
    }

    public void update(T... items) {
        mDao.updateInTx(items);
    }

    public void update(List items) {
        mDao.updateInTx(items);
    }

    public  T query(K key) {
        return  mDao.load(key);
    }

    public List queryAll() {
        return mDao.loadAll();
    }

    public List query(String where, String... params) {

        return mDao.queryRaw(where, params);
    }

    public QueryBuilder queryBuilder() {

        return mDao.queryBuilder();
    }

    public long count() {
        return mDao.count();
    }

    public void refresh(T item) {
        mDao.refresh(item);

    }

    public void detach(T item) {
        mDao.detach(item);
    }
}

一個實現類,第二個泛型參數是主鍵類型

 {
    public CardService(CardDao dao) {
        super(dao);
    }
}
public class PersonService extends BaseService {
    public PersonService(PersonDao dao) {
        super(dao);
    }
} data-snippet-id=ext.cd9ffcb8b2eae21ea54d4709356e925a data-snippet-saved=false data-csrftoken=uvnlqI2I-Bgjt_eeNkFvBvVloGMmCfRRN6VU data-codota-status=done>public class CardService extends BaseService {
    public CardService(CardDao dao) {
        super(dao);
    }
}
public class PersonService extends BaseService {
    public PersonService(PersonDao dao) {
        super(dao);
    }
}

編寫一個工具類獲得service

public class DbUtil {
    private static CardService cardService;
    private static PersonService personService;


    private static PersonDao getPersonDao() {
        return DbCore.getDaoSession().getPersonDao();
    }

    private static CardDao getCardDao() {
        return DbCore.getDaoSession().getCardDao();
    }

    public static CardService getCardService() {
        if (cardService == null) {
            cardService = new CardService(getCardDao());
        }
        return cardService;
    }

    public static PersonService getPersonService() {
        if (personService == null) {
            personService = new PersonService(getPersonDao());
        }
        return personService;
    }
}

在Application中初始化,並設置在清單文件中

public class App extends Application{
    @Override
    public void onCreate() {
        super.onCreate();
        DbCore.init(this);
    }
}

增刪改查,下面為單元測試的方法

 cards=new ArrayList();

        cards.add(c);
        cards.add(c1);


        mCardService.save(cards);

        c1.setNum(22222);

        mCardService.saveOrUpdate(cards);



    }


    public void testDelete(){
        Card c=new Card();
        c.setNum(333333333333333);
        c.setAddress(3333);

        mCardService.save(c);
        mCardService.delete(c);

        c=new Card();
        c.setNum(444444);
        c.setAddress(44444444);

        mCardService.save(c);
        mCardService.deleteByKey(c.getId());

    }

    public void testDelete1(){
        Card c=new Card();
        c.setNum(55555);
        c.setAddress(5555);



        Card c1=new Card();
        c1.setNum(666666);
        c1.setAddress(66666666);
        mCardService.save(c,c1);
        mCardService.delete(c, c1);

    }

    public void testDelete2(){
        Card c=new Card();
        c.setNum(55555);
        c.setAddress(5555);

        Card c1=new Card();
        c1.setNum(666666);
        c1.setAddress(66666666);
        List cards=new ArrayList();

        cards.add(c);
        cards.add(c1);

        mCardService.save(cards);
        mCardService.delete(cards);

    }

    public  void testDelete3(){
        mCardService.deleteAll();
    }

    public void testUpdate(){
        Card c=new Card();
        c.setNum(55555);
        c.setAddress(5555);

        mCardService.save(c);
        c.setNum(123456);
        mCardService.update(c);
    }
    public void testUpdate1(){
        Card c=new Card();
        c.setNum(55555);
        c.setAddress(5555);

        mCardService.save(c);
        c.setNum(123456);

        Card c1=new Card();
        c1.setNum(6666);
        c1.setAddress(66666);

        mCardService.save(c1);
        c1.setNum(654321);
        mCardService.update(c,c1);
    }

    public void testUpdate2(){
        Card c=new Card();
        c.setNum(aaaaa);
        c.setAddress(aaaaaaaaaa);

        mCardService.save(c);
        c.setNum(bbbbbbbbb);

        Card c1=new Card();
        c1.setNum(ccccc);
        c1.setAddress(cccccccc);

        mCardService.save(c1);
        c1.setNum(dddddddddd);

        List cards=new ArrayList();

        cards.add(c);
        cards.add(c1);
        mCardService.update(cards);
    }

    public void testQuery(){
        Card c=new Card();
        c.setNum(aaaaa111);
        c.setAddress(aaaaaaaa11111aa);

        mCardService.save(c);

        List cards = mCardService.queryAll();
        Log.e(TAG, cards + );

        Card query = mCardService.query(c.getId());
        Log.e(TAG, query + );

        List query1 = mCardService.query(where NUM=?, c.getNum());
        Log.e(TAG, query1 + );

        long count = mCardService.count();
        Log.e(TAG, count + );

        List list = mCardService.queryBuilder().where(CardDao.Properties.Num.eq(c.getNum())).list();
        Log.e(TAG, list + );
    }
} data-snippet-id=ext.89d1ad8ddbfba90c8536db59b57b26c9 data-snippet-saved=false data-csrftoken=n02wIPEW-drmeJwq73FEZ8IiYFsRv63QLKXY data-codota-status=done>public class ApplicationTest extends ApplicationTestCase {
    private PersonService mPersonService;
    private CardService mCardService;

    public ApplicationTest() {
        super(Application.class);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        DbCore.init(getContext());
        DbCore.enableQueryBuilderLog();
        mPersonService = DbUtil.getPersonService();
        mCardService = DbUtil.getCardService();
    }

    public void testSave(){
        Card c=new Card();
        c.setNum(3303241646813416463468);
        c.setAddress(杭州);

        mCardService.save(c);

        Person p=new Person();
        p.setName(張三);
        p.setHeight(178.00);
        p.setWeight(65.00);
        p.setCard(c);
        mPersonService.save(p);

        c.setPerson(p);
        mCardService.saveOrUpdate(c);

    }
    public void testSave1(){
        Card c=new Card();
        c.setNum(3303241646813416463468);
        c.setAddress(杭州);

        Card c1=new Card();
        c1.setNum(12121646813416463468);
        c1.setAddress(溫州);

        mCardService.save(c, c1);

        c.setNum(11111);
        mCardService.saveOrUpdate(c, c1);


    }

    public void testSave2(){
        Card c=new Card();
        c.setNum(3303241646813416463468);
        c.setAddress(杭州);

        Card c1=new Card();
        c1.setNum(12121646813416463468);
        c1.setAddress(溫州);

        List cards=new ArrayList();

        cards.add(c);
        cards.add(c1);


        mCardService.save(cards);

        c1.setNum(22222);

        mCardService.saveOrUpdate(cards);



    }


    public void testDelete(){
        Card c=new Card();
        c.setNum(333333333333333);
        c.setAddress(3333);

        mCardService.save(c);
        mCardService.delete(c);

        c=new Card();
        c.setNum(444444);
        c.setAddress(44444444);

        mCardService.save(c);
        mCardService.deleteByKey(c.getId());

    }

    public void testDelete1(){
        Card c=new Card();
        c.setNum(55555);
        c.setAddress(5555);



        Card c1=new Card();
        c1.setNum(666666);
        c1.setAddress(66666666);
        mCardService.save(c,c1);
        mCardService.delete(c, c1);

    }

    public void testDelete2(){
        Card c=new Card();
        c.setNum(55555);
        c.setAddress(5555);

        Card c1=new Card();
        c1.setNum(666666);
        c1.setAddress(66666666);
        List cards=new ArrayList();

        cards.add(c);
        cards.add(c1);

        mCardService.save(cards);
        mCardService.delete(cards);

    }

    public  void testDelete3(){
        mCardService.deleteAll();
    }

    public void testUpdate(){
        Card c=new Card();
        c.setNum(55555);
        c.setAddress(5555);

        mCardService.save(c);
        c.setNum(123456);
        mCardService.update(c);
    }
    public void testUpdate1(){
        Card c=new Card();
        c.setNum(55555);
        c.setAddress(5555);

        mCardService.save(c);
        c.setNum(123456);

        Card c1=new Card();
        c1.setNum(6666);
        c1.setAddress(66666);

        mCardService.save(c1);
        c1.setNum(654321);
        mCardService.update(c,c1);
    }

    public void testUpdate2(){
        Card c=new Card();
        c.setNum(aaaaa);
        c.setAddress(aaaaaaaaaa);

        mCardService.save(c);
        c.setNum(bbbbbbbbb);

        Card c1=new Card();
        c1.setNum(ccccc);
        c1.setAddress(cccccccc);

        mCardService.save(c1);
        c1.setNum(dddddddddd);

        List cards=new ArrayList();

        cards.add(c);
        cards.add(c1);
        mCardService.update(cards);
    }

    public void testQuery(){
        Card c=new Card();
        c.setNum(aaaaa111);
        c.setAddress(aaaaaaaa11111aa);

        mCardService.save(c);

        List cards = mCardService.queryAll();
        Log.e(TAG, cards + );

        Card query = mCardService.query(c.getId());
        Log.e(TAG, query + );

        List query1 = mCardService.query(where NUM=?, c.getNum());
        Log.e(TAG, query1 + );

        long count = mCardService.count();
        Log.e(TAG, count + );

        List list = mCardService.queryBuilder().where(CardDao.Properties.Num.eq(c.getNum())).list();
        Log.e(TAG, list + );
    }
}

 

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved