[Android]Android端ORM框架——RapidORM(v1.0)


以下內容為原創,歡迎轉載,轉載請注明

來自天天博客:http://www.cnblogs.com/tiantianbyconan/p/4748077.html 

 

Android上主流的ORM框架有很多,常用的有ORMLite、GreenDao等。

ORMLite:

-優點:API很友好,使用比較方便簡單穩定,相關功能比較完整。

-缺點:內部使用反射實現,性能並不是很好。

GreenDao:

-優點:性能很不錯,

-缺點:API卻不太友好,而且不支持復合主鍵,主鍵必須要有並且必須是long或者Long。持久類可以用它提供的模版生成,但是一旦使用了它的模版,持久類、DAO就不能隨意去修改,擴展性不是很好。如果不使用它的模版,代碼寫起來就很繁瑣。

 

所以結合了兩者重新寫了一個ORM:RapidORMhttps://github.com/wangjiegulu/RapidORM

特點:

1. 支持使用反射和非反射(模版生成)兩種方式實現執行SQL。

2. 支持復合主鍵

3. 支持任何主鍵類型

4. 兼容android原生的 android.database.sqlite.SQLiteDatabase 和SqlCipher的 net.sqlcipher.database.SQLiteDatabase

缺點:

1. 不支持鏈表查詢。

 

快速指南:

一、新建持久類Person:

 1 /**
 2  * Author: wangjie
 3  * Email: tiantian.china.2@gmail.com
 4  * Date: 6/25/15.
 5  */
 6 @Table(propertyClazz = PersonProperty.class)
 7 public class Person implements Serializable{
 8 
 9     @Column(primaryKey = true)
10     private Integer id;
11 
12     @Column(primaryKey = true)
13     private Integer typeId;
14 
15     @Column
16     private String name;
17 
18     @Column
19     private Integer age;
20 
21     @Column
22     private String address;
23 
24     @Column
25     private Long birth;
26 
27     @Column
28     private Boolean student;
29 
30     // getter/setter...
31 
32 }

 

1. Table注解用於標記這個類需要映射到數據表,RapidORM會創建這個表。

-name屬性:表示對應表的名稱,默認為類的simpleName。

-propertyClazz屬性:表示如果不使用反射執行sql時,需要的ModelProperty類的Class,RapidORM會自動在這個ModelProperty中去綁定需要執行SQL的數據。不填寫則表示使用默認的反射的方式執行SQL。具體后面會講到。

2. Column注解用語標記這個字段映射到的數據表的列(如果)。

-name屬性:表示對應列的名稱。默認為字段的名稱。

-primaryKey屬性:表示改列是否是主鍵,默認是false。(可以在多個字段都適用這個屬性,表示為復合主鍵)。

-autoincrement屬性:表示主鍵是否是自增長,只有該字段是主鍵並且只有一個主鍵並且是Integer或int類型才會生效。

-defaultValue屬性:表示該列默認值。

-notNull屬性:表示該列不能為空。

-unique屬性:表示該列唯一約束。

-uniqueCombo屬性:暫未實現。

-index屬性:暫未實現。

 

二、注冊持久類,並指定SQLiteOpenHelper:

新建類DatabaseFactory,繼承RapidORMConnection:

 1 /**
 2  * Author: wangjie
 3  * Email: tiantian.china.2@gmail.com
 4  * Date: 6/25/15.
 5  */
 6 public class DatabaseFactory extends RapidORMConnection<RapidORMDefaultSQLiteOpenHelperDelegate> {
 7     private static final int VERSION = 1;
 8 
 9     private static DatabaseFactory instance;
10 
11     public synchronized static DatabaseFactory getInstance() {
12         if (null == instance) {
13             instance = new DatabaseFactory();
14         }
15         return instance;
16     }
17 
18     private DatabaseFactory() {
19         super();
20     }
21 
22     @Override
23     protected RapidORMDefaultSQLiteOpenHelperDelegate getRapidORMDatabaseOpenHelper(@NonNull String databaseName) {
24         return new RapidORMDefaultSQLiteOpenHelperDelegate(new MyDatabaseOpenHelper(MyApplication.getInstance(), databaseName, VERSION));
25     }
26 
27     @Override
28     protected List<Class<?>> registerAllTableClass() {
29         List<Class<?>> allTableClass = new ArrayList<>();
30         allTableClass.add(Person.class);
31         // all table class
32         return allTableClass;
33     }
34 }

DatabaseFactory推薦使用單例,實現RapidORMConnection的getRapidORMDatabaseOpenHelper()方法,該方法需要返回一個RapidORMDatabaseOpenHelperDelegate或者它的子類對象,RapidORMDatabaseOpenHelperDelegate是SQLiteOpenHelper的委托,因為需要兼容android原生的 android.database.sqlite.SQLiteDatabase 和SqlCipher的 net.sqlcipher.database.SQLiteDatabase 兩種方式。

如果使用 android.database.sqlite.SQLiteDatabase ,則可以使用RapidORMDefaultSQLiteOpenHelperDelegate,然后構造方法中傳入真正的android.database.sqlite.SQLiteDatabase (也就是這里的MyDatabaseOpenHelper)即可,使用SqlCipher的方式后面再講。

還需要實現registerAllTableClass()方法,這里返回一個所有需要映射表的持久類Class集合。

 

三、在需要的地方進行初始化RapidORM(比如在登錄完成之后):

DatabaseFactory.getInstance().resetDatabase("hello_rapid_orm.db");

如上,調用resetDatabase()方法即可初始化數據庫。

 

四、編寫Dao:

新建PersonDaoImpl繼承BaseDaoImpl<Person>(這里簡略了PersonDao接口):

 1 /**
 2  * Author: wangjie
 3  * Email: tiantian.china.2@gmail.com
 4  * Date: 6/26/15.
 5  */
 6 public class PersonDaoImpl extends BaseDaoImpl<Person> {
 7     public PersonDaoImpl() {
 8         super(Person.class);
 9     }
10 
11 }

BaseDaoImpl中默認實現了下面的基本方法(T為范型,指具體的持久類):

-void insert(T model) throws Exception;  // 插入一條數據。

-void update(T model) throws Exception;  // 更新一條數據。

-void delete(T model) throws Exception;  // 刪除一條數據。

-void deleteAll() throws Exception;      // 刪除表中所有的數據

-void insertOrReplace(T model) throws Exception;    // 刪除或者替換(暫不支持)

-List<T> queryAll() throws Exception;      // 查詢表中所有數據

-List<T> rawQuery(String sql, String[] selectionArgs) throws Exception;      // 使用原生sql查詢表中所有的數據

-void rawExecute(String sql, Object[] bindArgs) throws Exception;        // 使用原生sql執行一條sql語句

-void insertInTx(T... models) throws Exception;          // 插入多條數據(在一個事務中)

-void insertInTx(Iterable<T> models) throws Exception;      // 同上

-void updateInTx(T... models) throws Exception;          // 更新多條數據(在一個事務中)

-void updateInTx(Iterable<T> models) throws Exception;      // 同上

-void deleteInTx(T... models) throws Exception;            // 刪除多條數據(在一個事務中)

-void deleteInTx(Iterable<T> models) throws Exception;        // 同上

-void executeInTx(RapidORMSQLiteDatabaseDelegate db, RapidOrmFunc1 func1) throws Exception; // 執行一個方法(可多個sql),在一個事務中

-void executeInTx(RapidOrmFunc1 func1) throws Exception;    // 同上

 

面向對象的方式使用Where和Builder來構建sql語句:

1. Where:

Where表示一系列的條件語句,含義與SQL中的where關鍵字一致。

支持的where操作:

-eq(String column, Object value)    // 相等條件判斷

-ne(String column, Object value)    // 不相等條件判斷

-gt(String column, Object value)     // 大於條件判斷

-lt(String column, Object value)     // 小於條件判斷

-ge(String column, Object value)     // 大於等於條件

-le(String column, Object value)     // 小於等於條件

-in(String column, Object... values)    // 包含條件

-ni(String column, Object... values)    // 不包含條件

-isNull(String column)          // null條件判斷

-notNull(String column)         // 不為null條件判斷

-between(String column, Object value1, Object value2)  // BETWEEN ... AND ..." condition

-like(String column, Object value)      // 模糊匹配條件

-Where raw(String rawWhere, Object... values)  // 原生sql條件

-and(Where... wheres)          // 多個Where與

-or(Where... wheres)          // 多個Where或

 

Where舉例:

1     Where.and(
2                 Where.like(PersonProperty.name.column, "%wangjie%"),
3                 Where.lt(PersonProperty.id.column, 200),
4                 Where.or(
5                         Where.between(PersonProperty.age.column, 19, 39),
6                         Where.isNull(PersonProperty.address.column)
7                 ),
8                 Where.eq(PersonProperty.typeId.column, 1)
9         )

如上,

Line2條件:name模糊匹配wangjie

Line3條件:id小於200

Line5條件:age在19到39之間

Line6條件:address不是null

Line8條件:typeId等於1

Line4條件:Line5條件和Line6條件是or關系;

Line1條件:Line2、Line3、Line4、Line8條件是and關系。

 

2. QueryBuilder:

QueryBuilder用於構建查詢語句。

-setWhere(Where where)    // 設置Where條件;

-setLimit(Integer limit)      // 設置limit

-addSelectColumn(String... selectColumn)    // 設置查詢的數據列名(可以調用多遍來設置多個,默認是查詢所有數據)

-addOrder(String column, boolean isAsc)     // 設置查詢結果的排序(可以調用多遍來設置多個)

 

QueryBuilder舉例:

 1     public List<Person> findPersonsByWhere() throws Exception {
 2         return queryBuilder()
 3                 .addSelectColumn(PersonProperty.id.column, PersonProperty.typeId.column, PersonProperty.name.column,
 4                         PersonProperty.age.column, PersonProperty.birth.column, PersonProperty.address.column)
 5                 .setWhere(Where.and(
 6                         Where.like(PersonProperty.name.column, "%wangjie%"),
 7                         Where.lt(PersonProperty.id.column, 200),
 8                         Where.or(
 9                                 Where.between(PersonProperty.age.column, 19, 39),
10                                 Where.isNull(PersonProperty.address.column)
11                         ),
12                         Where.eq(PersonProperty.typeId.column, 1)
13                 ))
14                 .addOrder(PersonProperty.id.column, false)
15                 .addOrder(PersonProperty.name.column, true)
16                 .setLimit(10)
17                 .query(this);
18     }

如上,通過queryBuilder()方法構建一個QueryBuilder,並設置查詢的列名、Where、排序、limit等參數,最后調用query()執行查詢。

 

3. UpdateBuilder:

UpdateBuilder用於構建更新語句。

-setWhere(Where where)    // 設置Where條件;

-addUpdateColumn(String column, Object value)    // 添加需要更新的字段;

 

UpdateBuilder舉例:

 1     public void updatePerson() throws Exception {
 2         long now = System.currentTimeMillis();
 3         updateBuilder()
 4                 .setWhere(Where.and(
 5                         Where.like(PersonProperty.name.column, "%wangjie%"),
 6                         Where.lt(PersonProperty.id.column, 200),
 7                         Where.or(
 8                                 Where.between(PersonProperty.age.column, 19, 39),
 9                                 Where.isNull(PersonProperty.address.column)
10                         ),
11                         Where.eq(PersonProperty.typeId.column, 1)
12                 ))
13                 .addUpdateColumn(PersonProperty.birth.column, now)
14                 .addUpdateColumn(PersonProperty.address.column, "address_" + now).update(this);
15     }

如上,通過updateBuilder()方法構建一個UpdateBuilder,並設置要更新的字段,最后調用update()執行查詢。

 

4. DeleteBuilder: 

DeleteBuilder用於構建刪除語句。

-setWhere(Where where)    // 設置Where條件;

 

DeleteBuilder舉例:

 1     public void deletePerson() throws Exception {
 2         deleteBuilder()
 3                 .setWhere(Where.and(
 4                         Where.like(PersonProperty.name.column, "%wangjie%"),
 5                         Where.lt(PersonProperty.id.column, 200),
 6                         Where.or(
 7                                 Where.between(PersonProperty.age.column, 19, 39),
 8                                 Where.isNull(PersonProperty.address.column)
 9                         ),
10                         Where.eq(PersonProperty.typeId.column, 1)
11                 ))
12                 .delete(this);
13     }

如上,通過deleteBuilder()方法構建一個DeleteBuilder,並設置Where條件,最后調用delete()執行查詢。

 

使用模版生成ModelProperty:

如果你打算使用非反射的方式執行sql,則可以使用ModelPropertyGenerator模版來生成

1. 新建一個類,在main方法中執行:

/**
 * Author: wangjie
 * Email: tiantian.china.2@gmail.com
 * Date: 7/2/15.
 */
public class MyGenerator {
    public static void main(String[] args) throws Exception {

        Class tableClazz = Person.class;
        new ModelPropertyGenerator().generate(tableClazz,
                "example/src/main/java",
                tableClazz.getPackage().getName() + ".config");

    }

}

如上,generate()方法參數如下:

generate(Class tableClazz, String outerDir, String packageName)

參數一:要生成的Property持久類的Class

參數二:生成的ModelProperty類文件存放目錄

參數三:生成的ModelProperty類文件的包名

執行完畢后,就會在com.wangjie.rapidorm.example.database.model.config包下生成如下的ModelProperty:

  1 // THIS CODE IS GENERATED BY RapidORM, DO NOT EDIT.
  2 /**
  3 * Property of Person
  4 */
  5 public class PersonProperty implements IModelProperty<Person> {
  6 
  7     public static final ModelFieldMapper id = new ModelFieldMapper(0, "id", "id");
  8     public static final ModelFieldMapper typeId = new ModelFieldMapper(1, "typeId", "typeId");
  9     public static final ModelFieldMapper name = new ModelFieldMapper(2, "name", "name");
 10     public static final ModelFieldMapper age = new ModelFieldMapper(3, "age", "age");
 11     public static final ModelFieldMapper address = new ModelFieldMapper(4, "address", "address");
 12     public static final ModelFieldMapper birth = new ModelFieldMapper(5, "birth", "birth");
 13     public static final ModelFieldMapper student = new ModelFieldMapper(6, "student", "student");
 14 
 15     public PersonProperty() {
 16     }
 17 
 18 
 19     @Override
 20     public void bindInsertArgs(Person model, List<Object> insertArgs) {
 21         Integer id = model.getId();
 22         insertArgs.add(null == id ? null : id);
 23 
 24         Integer typeId = model.getTypeId();
 25         insertArgs.add(null == typeId ? null : typeId);
 26 
 27         String name = model.getName();
 28         insertArgs.add(null == name ? null : name);
 29 
 30         Integer age = model.getAge();
 31         insertArgs.add(null == age ? null : age);
 32 
 33         String address = model.getAddress();
 34         insertArgs.add(null == address ? null : address);
 35 
 36         Long birth = model.getBirth();
 37         insertArgs.add(null == birth ? null : birth);
 38 
 39         Boolean student = model.isStudent();
 40         insertArgs.add(null == student ? null : student ? 1 : 0);
 41 
 42     }
 43 
 44     @Override
 45     public void bindUpdateArgs(Person model, List<Object> updateArgs) {
 46         String name = model.getName();
 47         updateArgs.add(null == name ? null : name);
 48 
 49         Integer age = model.getAge();
 50         updateArgs.add(null == age ? null : age);
 51 
 52         String address = model.getAddress();
 53         updateArgs.add(null == address ? null : address);
 54 
 55         Long birth = model.getBirth();
 56         updateArgs.add(null == birth ? null : birth);
 57 
 58         Boolean student = model.isStudent();
 59         updateArgs.add(null == student ? null : student ? 1 : 0);
 60 
 61     }
 62 
 63     @Override
 64     public void bindPkArgs(Person model, List<Object> pkArgs) {
 65         Integer id = model.getId();
 66         pkArgs.add(null == id ? null : id);
 67 
 68         Integer typeId = model.getTypeId();
 69         pkArgs.add(null == typeId ? null : typeId);
 70 
 71     }
 72 
 73     @Override
 74     public Person parseFromCursor(Cursor cursor) {
 75         Person model = new Person();
 76         int index;
 77         index = cursor.getColumnIndex("id");
 78         if(-1 != index){
 79             model.setId(cursor.isNull(index) ? null : (cursor.getInt(index)));
 80         }
 81 
 82         index = cursor.getColumnIndex("typeId");
 83         if(-1 != index){
 84             model.setTypeId(cursor.isNull(index) ? null : (cursor.getInt(index)));
 85         }
 86 
 87         index = cursor.getColumnIndex("name");
 88         if(-1 != index){
 89             model.setName(cursor.isNull(index) ? null : (cursor.getString(index)));
 90         }
 91 
 92         index = cursor.getColumnIndex("age");
 93         if(-1 != index){
 94             model.setAge(cursor.isNull(index) ? null : (cursor.getInt(index)));
 95         }
 96 
 97         index = cursor.getColumnIndex("address");
 98         if(-1 != index){
 99             model.setAddress(cursor.isNull(index) ? null : (cursor.getString(index)));
100         }
101 
102         index = cursor.getColumnIndex("birth");
103         if(-1 != index){
104             model.setBirth(cursor.isNull(index) ? null : (cursor.getLong(index)));
105         }
106 
107         index = cursor.getColumnIndex("student");
108         if(-1 != index){
109             model.setStudent(cursor.isNull(index) ? null : (cursor.getInt(index) == 1));
110         }
111 
112         return model;
113     }
114 
115 }

注意:此Property類一旦生成,則不能修改;如果該持久類相關的注解屬性改變,則需要重新生成這個Property類。

2. 在相應的持久類的@Table注解中設置propertyClazz:

1 @Table(propertyClazz = PersonProperty.class)
2 public class Person implements Serializable{

 

如何兼容SqlCipher

1. 新建MySQLCipherOpenHelper,繼承net.sqlcipher.database.SQLiteOpenHelper:

 1 import android.content.Context;
 2 import com.wangjie.rapidorm.core.dao.DatabaseProcessor;
 3 import com.wangjie.rapidorm.core.delegate.database.RapidORMSQLiteDatabaseDelegate;
 4 import net.sqlcipher.database.SQLiteDatabase;
 5 import net.sqlcipher.database.SQLiteDatabaseHook;
 6 import net.sqlcipher.database.SQLiteOpenHelper;
 7 
 8 /**
 9  * Author: wangjie
10  * Email: tiantian.china.2@gmail.com
11  * Date: 8/17/15.
12  */
13 public class MySQLCipherOpenHelper extends SQLiteOpenHelper {
14 
15     private RapidORMSQLiteDatabaseDelegate rapidORMSQLiteDatabaseDelegate;
16 
17     public MySQLCipherOpenHelper(Context context, String name, int version) {
18         super(context, name, null, version);
19     }
20 
21     public MySQLCipherOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
22         super(context, name, factory, version);
23     }
24 
25     public MySQLCipherOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version, SQLiteDatabaseHook hook) {
26         super(context, name, factory, version, hook);
27     }
28 
29     @Override
30     public void onCreate(SQLiteDatabase db) {
31 //        super.onCreate(db);
32         rapidORMSQLiteDatabaseDelegate = new MySQLCipherDatabaseDelegate(db);
33         DatabaseProcessor databaseProcessor = DatabaseProcessor.getInstance();
34         for (Class<?> tableClazz : databaseProcessor.getAllTableClass()) {
35             databaseProcessor.createTable(rapidORMSQLiteDatabaseDelegate, tableClazz, true);
36         }
37     }
38 
39     @Override
40     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
41 //        super.onUpgrade(db, oldVersion, newVersion);
42         rapidORMSQLiteDatabaseDelegate = new MySQLCipherDatabaseDelegate(db);
43         DatabaseProcessor databaseProcessor = DatabaseProcessor.getInstance();
44         // todo: dev only!!!!!
45         databaseProcessor.dropAllTable(rapidORMSQLiteDatabaseDelegate);
46 
47     }
48 }

 

2. 新建MySQLCipherDatabaseDelegate繼承RapidORMSQLiteDatabaseDelegate,並實現以下的方法:

 1 import android.database.Cursor;
 2 import android.database.SQLException;
 3 import com.wangjie.rapidorm.core.delegate.database.RapidORMSQLiteDatabaseDelegate;
 4 import net.sqlcipher.database.SQLiteDatabase;
 5 
 6 /**
 7  * Author: wangjie
 8  * Email: tiantian.china.2@gmail.com
 9  * Date: 8/17/15.
10  */
11 public class MySQLCipherDatabaseDelegate extends RapidORMSQLiteDatabaseDelegate<SQLiteDatabase> {
12     public MySQLCipherDatabaseDelegate(SQLiteDatabase db) {
13         super(db);
14     }
15 
16     @Override
17     public void execSQL(String sql) throws SQLException {
18         db.execSQL(sql);
19     }
20 
21     @Override
22     public boolean isDbLockedByCurrentThread() {
23         return db.isDbLockedByCurrentThread();
24     }
25 
26     @Override
27     public void execSQL(String sql, Object[] bindArgs) throws Exception {
28         db.execSQL(sql, bindArgs);
29     }
30 
31     @Override
32     public Cursor rawQuery(String sql, String[] selectionArgs) {
33         return db.rawQuery(sql, selectionArgs);
34     }
35 
36     @Override
37     public void beginTransaction() {
38         db.beginTransaction();
39     }
40 
41     @Override
42     public void setTransactionSuccessful() {
43         db.setTransactionSuccessful();
44     }
45 
46     @Override
47     public void endTransaction() {
48         db.endTransaction();
49     }
50 
51     @Override
52     public void close() {
53         db.close();
54     }
55 }

注意這里的import,這里的SQLiteDatabase需要導入 net.sqlcipher.database.SQLiteDatabase 。

 

3. 新建MySQLCipherOpenHelperDelegate繼承RapidORMDatabaseOpenHelperDelegate,實現如下方法:

 1 import com.wangjie.rapidorm.core.delegate.openhelper.RapidORMDatabaseOpenHelperDelegate;
 2  3 
 4 /**
 5  * Author: wangjie
 6  * Email: tiantian.china.2@gmail.com
 7  * Date: 6/18/15.
 8  */
 9 public class MySQLCipherOpenHelperDelegate extends RapidORMDatabaseOpenHelperDelegate<MySQLCipherOpenHelper, MySQLCipherOpenHelperDelegate> {
10     public MySQLCipherOpenHelperDelegate(MySQLCipherOpenHelper sqLiteOpenHelper) {
11         super(sqLiteOpenHelper);
12     }
13 
14     public static final String SECRET_KEY = "1234567890abcdef";
15 
16     @Override
17     public MySQLCipherOpenHelperDelegate getReadableDatabase() {
18         return new MySQLCipherDatabaseDelegate(openHelper.getReadableDatabase(SECRET_KEY));
19     }
20 
21     @Override
22     public MySQLCipherOpenHelperDelegate getWritableDatabase() {
23         return new MySQLCipherDatabaseDelegate(openHelper.getWritableDatabase(SECRET_KEY));
24     }
25 
26 }

 

4. 在DatabaseFactory中使用SqlCipher版本:

 1 /**
 2  * Author: wangjie
 3  * Email: tiantian.china.2@gmail.com
 4  * Date: 6/25/15.
 5  */
 6 public class DatabaseFactory extends RapidORMConnection<MySQLCipherOpenHelperDelegate> {
 7     private static final int VERSION = 1;
 8 
 9     private static DatabaseFactory instance;
10 
11     public synchronized static DatabaseFactory getInstance() {
12         if (null == instance) {
13             instance = new DatabaseFactory();
14         }
15         return instance;
16     }
17 
18     private DatabaseFactory() {
19         super();
20     }
21 
22     @Override
23     protected MySQLCipherOpenHelperDelegate getRapidORMDatabaseOpenHelper(@NonNull String databaseName) {
24         return new MySQLCipherOpenHelperDelegate(new MySQLCipherOpenHelper(applicationContext, databaseName, VERSION));
25     }
26 
27     @Override
28     protected List<Class<?>> registerAllTableClass() {
29         List<Class<?>> allTableClass = new ArrayList<>();
30         allTableClass.add(Person.class);
31         // register all table class here...
32         return allTableClass;
33     }
34 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM