Android中使用OrmLite(一):表創建及增刪改查

OrmLite是一個輕量級的ORM框架,面向JAVA語言。也是時下流行的Android的ORM框架之一。在Android中使用Sqlite數據,如果又不想寫SQL,OrmLite或許是個不錯的選擇。


使用OrmLite,首先要在gradle配置依賴 compile 'com.j256.ormlite:ormlite-android:4.48'
也可以去ormlite官網下載查看文檔 http://ormlite.com/

1.表創建

然後要要創建一個實體類,對應表結構。OrmLite提供了兩個註解,@DatabaseField 代表表列名,@DatabaseTable 表名 tableName值爲數據庫中表的真實名稱。下列的User類必須有一個無參數的構造函數。

需要指定一個字段爲唯一標誌,必須爲int, Integer ,long, Long, Uuid類型
數據庫中的記錄通過定義爲唯一的特殊字段成爲唯一標識。記錄不是必須有唯一標識字段當時很多DAO操作(更新、刪除、刷新)都需要一個唯一標識字段。這個標識要麼用戶提供要麼數據庫自動生成。標識字段有表中唯一的值並且如果你用DAO根據id查詢、刪除、刷新或者更新指定行的時候他們必須存在。爲了配置一個成員變量作爲標識成員,你應該使用下面三個設置之一(而且必須使用一個):@DatabaseField: id, generatedId, generatedIdSequence 。 
@DatabaseField(id = true)指定哪個字段爲主鍵
@DatabaseField(generatedId = true)自動增加的ID
@DatabaseField(generatedIdSequence = true) 設置序列名來匹配已經存在的schema,你可以使用generatedIdSequence指定序列名的值。

這樣纔可以使用ID來做刪除,修改,查詢等操作。否則調用相關方法拋出
Cannot query-for-id with class xxx.xxx.xxx.User because it doesn't have an id field相關異常。

@DatabaseTable(tableName = "t_user")
public class User {

    @DatabaseField(generatedId =true)
    private int id;

    @DatabaseField
    private String name;

    public User(int id, String name) {
        this.name = name;
        this.id = id;
    }

    public User() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}


Android中使用Sqlite需要繼承自SQLiteOpenHelper,要使用ormlite需要繼承OrmLiteSqliteOpenHelper,來實現一些創建數據庫,創建表,更新表的操作。TableUtils是個工具類,主要提供表的創建,表的移除等操作。

public class DbHelper extends OrmLiteSqliteOpenHelper {

    private DbHelper(Context context) {
        //參數:上下文,數據庫名稱,cursor factory,數據庫版本.
        super(context, "test.db", null, 1);
    }

    //第一次操作數據庫時候,被調用
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
        try {
            TableUtils.createTable(connectionSource, User.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //當數據庫版本升級的時候,被調用
    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i1) {
        try {
            //這裏只是粗暴的移除了舊錶,新建新表,這樣會導致數據丟失,現實一般不這麼做
            TableUtils.dropTable(connectionSource, User.class, true);
            onCreate(sqLiteDatabase, connectionSource);
        } catch (SQLException e) {Orm
            e.printStackTrace();
        }
    }

    //實現一個單例返回DbHelper實例
    private static DbHelper helper;
   
    public static DbHelper getHelper(Context context) {
        if (helper == null) {
            helper = new DbHelper(context);
        }
        return helper;
    }
}

2.表的增刪改查
首先通過上述的單例類獲取一個OrmLiteSqliteOpenHelper的實例,該類中有個getDao(Class<T> clazz)方法可以獲取到對應實體的dao對象,參數clazz爲表對應的實體的class對象,例如User.class 。

通過getDao返回一個Dao<T, ID>的實例,dao中有增刪改查的方法。

從helper獲取一個dao的實例

private Dao<User, Integer> userDao;

public UserDao() {
    init();
}

private void init() {
    DbHelper dbHelper = DbHelper.getHelper(ContextProvider.getApplicationContext());
    try {
        userDao = dbHelper.getDao(User.class);
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

在表中添加一條記錄
public int create(T data) throws SQLException;

在表中添加一條記錄,如果表不存在這條數據,根據設置的主鍵來判斷是否存在
public T createIfNotExists(T data) throws SQLException;

在表中添加一條記錄,如果存在則更新主鍵對應的一條記錄,
public CreateOrUpdateStatus createOrUpdate(T data) throws SQLException;

User user = new User();
userDao.create(user);
userDao.createOrUpdate(user);
userDao.createIfNotExists(user);


刪除

根據傳入實體刪除
public int delete(T data) throws SQLException;

根據ID刪除
public int deleteById(ID id) throws SQLException;

根據集合刪除
public int delete(Collection<T> datas) throws SQLException;

根據id集合刪除
public int deleteIds(Collection<ID> ids) throws SQLException;

userDao.deleteIds(ids);
userDao.deleteById(id);
userDao.delete(user);
userDao.delete(list);

更新

//根據傳入的實體更新數據,ID爲唯一標誌
public int update(T data) throws SQLException;

//更新ID,其他值不變
public int updateId(T data, ID newId) throws SQLException;

mDao.update(new User(1, "update"));
//更新id指定行的數據

mDao.updateId(new User(mId, mName), 10000);
//把當前的行id更新爲10000

查詢

根據唯一標誌id檢索一條記錄,如果id爲
public T queryForId(ID id) throws SQLException;

查詢匹配到的所有行中的第一個
public T queryForFirst(PreparedQuery<T> preparedQuery) throws SQLException;

返回表中所有條目,可導致大量數據導入內存,應該使用iterator方法來代替此方法
public List<T> queryForAll() throws SQLException;

查詢指定字段value等於查詢值的行: where fieldName = value
public List<T> queryForEq(String fieldName, Object value) throws SQLException;

匹配傳入實體(字段不能爲默認值,null,false,0,0.0等)的每個字段的值,每個條件進行and操作,返回的結果,可能導致SQL quote escaping
public List<T> queryForMatching(T matchObj) throws SQLException;

同上述方法,不會導致SQL quote escaping
public List<T> queryForMatchingArgs(T matchObj) throws SQLException;

根據傳入的字段與value值的map匹配查詢
public List<T> queryForFieldValues(Map<String, Object> fieldValues) throws SQLException;

 根據傳入的字段與value值的map匹配查詢
public List<T> queryForFieldValuesArgs(Map<String, Object> fieldValues) throws SQLException;

查詢與傳入實體id相等的數據行
public T queryForSameId(T data) throws SQLException;

mDao.queryForAll();
mDao.queryForId(mId);



發佈了30 篇原創文章 · 獲贊 62 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章