GreenDao best practices for the Android ORM Series

Source: Internet
Author: User

GreenDao best practices for the Android ORM Series

GreenDAO Is An ORM solution that helps Android Developers quickly map Java objects to SQLite database forms. by using a simple object-oriented API, developers can store, update, delete, and query Java objects.

GreenDao has two projects: one is the generator project for generating dao and model, the other is the java project, and the other is the core jar package for android. Before using it, we must convert it into dao and model.

Add dependencies first.

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

Create a db package under our package name, and create a dao and model package and a generator package under the db, just like.

In generatZ tables? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> flock/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 ");Indicates the version number of the created database and the default java package. If you do not modify the default package name, the generated dao and model will be under this package. Here we modify the package name of dao.Schema. setdefajavjavapackagedao ("cn.edu. zafu. greendao. db. dao ");In the generated model, we may need to add some information of our own, but we do not want to disappear the next generation, so we can useSchema. enableKeepSectionsByDefault ();, The following labels are displayed in the model class.

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

You only need to add the information you need to the three, the distribution represents the introduced package, field, method. The information is retained.

Schema. enableActiveEntitiesByDefault ();Indicates whether the object class supports active. If you have used the yii framework in php, it should be clear that the object class can perform crud operations directly. We don't need to enable it. If it is enabled, the entity classes support update, refresh, deleted, and other operations.

Use it laterSchema. addEntity ()Add an Entity object to the function, that is, the corresponding object class. Add the field by adding the attribute method addProperty series method, and finally callNew DaoGenerator (). generateAll (schema, "./app/src/main/java ");Method to generate dao and model.

The generation process is also very simple. Right-click the class and click run.

After generation, the console will output

Then we compile a core helper class. Used to obtain DaoMaster and 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;    }}

Next is the basic generic 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); }}
                  
                 
                
               
              
             
            
           
          
        
       
      
     
    
   
  
 

One implementation class, and the second generic parameter is the primary key type

 {    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);    }}
    
   
 

Compile a tool class to obtain the 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;    }}

Initialize in Application and set it in the configuration file

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

Add, delete, modify, and query. The following is the unit test method.

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 (dddddddddddd); 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 (Hangzhou); mCardService. save (c); Person p = new Person (); p. setName (zhangsan); 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 (Hangzhou); Card c1 = new Card (); c1.setNum (12121646813416463468); c1.setAddress (Wenzhou); mCardService. save (c, c1); c. setNum (11111); mCardService. saveOrUpdate (c, c1);} public void testSave2 () {Card c = new Card (); c. setNum (3303241646813416463468); c. setAddress (Hangzhou); Card c1 = new Card (); c1.setNum (12121646813416463468); c1.setAddress (Wenzhou); 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 (dddddddddddd); 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 + );}}
                  
                 
                
               
              
             
            
           
          
        
       
      
     
    
   
  
 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.