码迷,mamicode.com
首页 > 移动开发 > 详细

[转]Android ORM系列之GreenDao最佳实践

时间:2016-02-17 22:14:56      阅读:540      评论:0      收藏:0      [点我收藏+]

标签:

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的包,就像下图。
技术分享

在generator包下,新建一个生成dao和model的类GreenDaoGenerator,在里面加入代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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类中有如下这些标示

1
2
3
4
5
6
7
8
// 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
public class BaseService<T, K> {
    private AbstractDao<T, K> 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<T> items) {
        mDao.insertInTx(items);
    }
 
    public void saveOrUpdate(T item) {
        mDao.insertOrReplace(item);
    }
 
    public void saveOrUpdate(T... items) {
        mDao.insertOrReplaceInTx(items);
    }
 
    public void saveOrUpdate(List<T> 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<T> 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<T> items) {
        mDao.updateInTx(items);
    }
 
    public  T query(K key) {
        return  mDao.load(key);
    }
 
    public List<T> queryAll() {
        return mDao.loadAll();
    }
 
    public List<T> query(String where, String... params) {
 
        return mDao.queryRaw(where, params);
    }
 
    public QueryBuilder<T> 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);
    }
}

一个实现类,第二个泛型参数是主键类型

1
2
3
4
5
6
7
8
9
10
public class CardService extends BaseService<Card,Long> {
    public CardService(CardDao dao) {
        super(dao);
    }
}
public class PersonService extends BaseService<Person,Long> {
    public PersonService(PersonDao dao) {
        super(dao);
    }
}

编写一个工具类获得service

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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中初始化,并设置在清单文件中

1
2
3
4
5
6
7
public class App extends Application{
    @Override
    public void onCreate() {
        super.onCreate();
        DbCore.init(this);
    }
}

增删改查,下面为单元测试的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
public class ApplicationTest extends ApplicationTestCase<Application> {
    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&lt;Card&gt; cards=new ArrayList&lt;Card&gt;();
 
        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&lt;Card&gt; cards=new ArrayList&lt;Card&gt;();
 
        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<Card> cards=new ArrayList<Card>();
 
        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&lt;Card&gt; cards = mCardService.queryAll();
        Log.e("TAG", cards + "");
 
        Card query = mCardService.query(c.getId());
        Log.e("TAG", query + "");
 
        List&lt;Card&gt; query1 = mCardService.query("where NUM=?", c.getNum());
        Log.e("TAG", query1 + "");
 
        long count = mCardService.count();
        Log.e("TAG", count + "");
 
        List&lt;Card&gt; list = mCardService.queryBuilder().where(CardDao.Properties.Num.eq(c.getNum())).list();
        Log.e("TAG", list + "");
    }
}

关于关联关系的映射,下一篇文章细说。

源码下载。

[转]Android ORM系列之GreenDao最佳实践

标签:

原文地址:http://www.cnblogs.com/qianyukun/p/5196545.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!