Android Orm框架(GreenDao)

android項目里面很多都會有使用sqlite來保存數據。原生api真心不好使啊,要寫超多超多的代碼,還要寫顧慮很多細節問題。于是乎就想偷懶了,干脆去網上找個orm框架吧!

Ok,google it。篩選一下,就鎖定了ormlite和greendao。簡單看了一下,ormlite簡單好用,比較符合JavaEE開發者使用習慣,注解真的很好用啊!再去greendao官網逛逛,他說我們的目標是:

最牛掰的性能

超好用的API

為Android大大優化

最小的內存使用

******

再翻翻看,還有同ormlite的性能對比:

上面可以看到,greeendao的insert和update效率要比ormlite快兩倍左右,load更是夸張到4倍多。尼瑪也太厲害了吧,優化這么狠。這么一大堆好處,還不趕緊使使。

我們可以在官網上直接下來,也可去github項目主頁上下載源碼。建議去下載github哈,因為有源碼有列子,比較直觀易懂。源碼使用gradle構建,需要安裝gradle插件。其實真正也只有依賴一個freemaker.jar,直接網上下載一個就好。下面新建一個java工程,注意是java工程不是android工程。導入freemaker.jar和greendao-generator.jar,加入到build path。建一個如下的類:

?

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

56publicclassDaoGenerator {

publicstaticvoidmain(String[] args)throwsException {

// first parameter for version, second for default generate package

Schema schema =newSchema(1,"com.xckevin.example.model");

addNote(schema);

addCustomerOrder(schema);

addUser(schema);

// set dao class generate package

schema.setDefaultJavaPackageDao("com.xckevin.example.dao");

// keep custom code block

schema.enableKeepSectionsByDefault();

newDaoGenerator().generateAll(schema,"../GreenDaoExample/src");

}

privatestaticvoidaddNote(Schema schema) {

Entity note = schema.addEntity("Note");

note.addIdProperty();

note.addStringProperty("text").notNull();

note.addStringProperty("comment");

note.addDateProperty("date");

}

privatestaticvoidaddUser(Schema schema) {

Entity user = schema.addEntity("User");

user.setTableName("t_user");

user.addIdProperty();

user.addStringProperty("account").unique();

user.addStringProperty("password");

user.addDateProperty("birthday");

user.addShortProperty("gender");

user.addIntProperty("height");

user.addFloatProperty("weight");

user.addDateProperty("registerTime");

user.implementsInterface("Jsonable");

}

privatestaticvoidaddCustomerOrder(Schema schema) {

Entity customer = schema.addEntity("Customer");

customer.addIdProperty();

customer.addStringProperty("name").notNull();

Entity order = schema.addEntity("Order");

order.setTableName("ORDERS");// "ORDER" is a reserved keyword

order.addIdProperty();

Property orderDate = order.addDateProperty("date").getProperty();

Property customerId = order.addLongProperty("customerId").notNull().getProperty();

order.addToOne(customer, customerId);

ToMany customerToOrders = customer.addToMany(order, customerId);

customerToOrders.setName("orders");

customerToOrders.orderAsc(orderDate);

}

}

代碼號簡單的話,看名字就知道是什么意思了。greendao支持各種類型的哇,還支持一對一、一對多、多對多的關系,很強悍!直接運行,代碼生成

自動生成model和dao,倍兒爽!隨便看一個model類:

?

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

123packagecom.xckevin.example.model;

// THIS CODE IS GENERATED BY greenDAO, EDIT ONLY INSIDE THE "KEEP"-SECTIONS

// KEEP INCLUDES - put your custom includes here

importorg.json.JSONException;

importorg.json.JSONObject;

// KEEP INCLUDES END

/**

* Entity mapped to table t_user.

*/

publicclassUserimplementsJsonable {

privateLong id;

privateString account;

privateString password;

privatejava.util.Date birthday;

privateShort gender;

privateInteger height;

privateFloat weight;

privatejava.util.Date registerTime;

// KEEP FIELDS - put your custom fields here

// KEEP FIELDS END

publicUser() {

}

publicUser(Long id) {

this.id = id;

}

publicUser(Long id, String account, String password, java.util.Date birthday, Short gender, Integer height, Float weight, java.util.Date registerTime) {

this.id = id;

this.account = account;

this.password = password;

this.birthday = birthday;

this.gender = gender;

this.height = height;

this.weight = weight;

this.registerTime = registerTime;

}

publicLong getId() {

returnid;

}

publicvoidsetId(Long id) {

this.id = id;

}

publicString getAccount() {

returnaccount;

}

publicvoidsetAccount(String account) {

this.account = account;

}

publicString getPassword() {

returnpassword;

}

publicvoidsetPassword(String password) {

this.password = password;

}

publicjava.util.Date getBirthday() {

returnbirthday;

}

publicvoidsetBirthday(java.util.Date birthday) {

this.birthday = birthday;

}

publicShort getGender() {

returngender;

}

publicvoidsetGender(Short gender) {

this.gender = gender;

}

publicInteger getHeight() {

returnheight;

}

publicvoidsetHeight(Integer height) {

this.height = height;

}

publicFloat getWeight() {

returnweight;

}

publicvoidsetWeight(Float weight) {

this.weight = weight;

}

publicjava.util.Date getRegisterTime() {

returnregisterTime;

}

publicvoidsetRegisterTime(java.util.Date registerTime) {

this.registerTime = registerTime;

}

// KEEP METHODS - put your custom methods here

@Override

publicUser parse(JSONObject jsonObj) {

// TODO Auto-generated method stub

try{

id = jsonObj.getLong("id");

account = jsonObj.getString("account");

returnthis;

}catch(JSONException e) {

e.printStackTrace();

}

returnnull;

}

// KEEP METHODS END

}

注意上面的// KEEP代碼塊中是手動加入了,當設置了

?

1

schema.enableKeepSectionsByDefault

后,該部分代碼塊在下次更新的時候會保留下來。

dao類中也有各種基本的方法,如insert,update,delete等等。基本可能完成大部分需求了,終于不用寫那么繁瑣的數據庫操作啦!

再看看怎么在client獲取到dao,注意client要加入greendao.jar哦。有了dao就可以對數據庫各種操作了!

?

1

2

3

4

5DevOpenHelper helper =newDaoMaster.DevOpenHelper(this,"notes-db",null);

db = helper.getWritableDatabase();

daoMaster =newDaoMaster(db);

daoSession = daoMaster.newSession();

userDao = daoSession.getUserDao();

總體來說,ormlite使用簡單,學習成本低,容易上手,效率比greendao偏慢一點。greendao耦合性高,使用時要另外使用一個java工程創建,開始環境搭建比較麻煩,但是一旦上手還是十分容易使用的,并且效率最好。個人還是推薦使用greendao。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容