Android 数据库框架ormlite 使用精要
Android 數(shù)據(jù)庫(kù)框架ormlite 使用精要
前言
本篇博客記錄一下筆者在實(shí)際開發(fā)中使用到的一個(gè)數(shù)據(jù)庫(kù)框架,這個(gè)可以讓我們快速實(shí)現(xiàn)數(shù)據(jù)庫(kù)操作,避免頻繁手寫sql,提高我們的開發(fā)效率,減少出錯(cuò)的機(jī)率。
ormlite是什么?
首先可以去它的官網(wǎng)看看www.ormlite.com,它的英文全稱是Object Relational Mapping,意思是對(duì)象關(guān)系映射;如果接觸過(guò)Java EE開發(fā)的,一定知道Java Web開發(fā)就有一個(gè)類似的數(shù)據(jù)庫(kù)映射框架——Hibernate。簡(jiǎn)單來(lái)說(shuō),就是我們定義一個(gè)實(shí)體類,利用這個(gè)框架,它可以幫我們吧這個(gè)實(shí)體映射到我們的數(shù)據(jù)庫(kù)中,在Android中是SQLite,數(shù)據(jù)中的字段就是我們定義實(shí)體的成員變量。
為什么要用ormlite?
先說(shuō)說(shuō)優(yōu)點(diǎn)
缺點(diǎn)
如何使用?
導(dǎo)入jar包到項(xiàng)目libs文件夾下
到http://ormlite.com/releases/下載相應(yīng)版本的jar,下載最新的,目前是最新版本4.49。我們下載穩(wěn)定的4.48即可。
繼承OrmLiteSqliteOpenHelper類定義數(shù)據(jù)庫(kù)幫助類
package com.devilwwj.ormlite.db;import java.sql.SQLException; import java.util.HashMap; import java.util.Map;import android.content.Context; import android.database.sqlite.SQLiteDatabase;import com.devilwwj.ormlite.model.Img; import com.devilwwj.ormlite.model.PackageInfo; import com.devilwwj.ormlite.model.Photographer; import com.devilwwj.ormlite.model.Theme; import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.table.TableUtils;/*** 功能:數(shù)據(jù)庫(kù)幫助類* @author devilwwj**/ public class DBHelper extends OrmLiteSqliteOpenHelper {/*** 數(shù)據(jù)庫(kù)名字*/private static final String DB_NAME = "test.db";/*** 數(shù)據(jù)庫(kù)版本*/private static final int DB_VERSION = 1;/*** 用來(lái)存放Dao的地圖*/private Map<String, Dao> daos = new HashMap<String, Dao>();private static DBHelper instance;/*** 獲取單例* @param context* @return*/public static synchronized DBHelper getHelper(Context context) {context = context.getApplicationContext();if (instance == null) {synchronized (DBHelper.class) {if (instance == null) {instance = new DBHelper(context);}}}return instance;}/*** 構(gòu)造方法* @param context*/public DBHelper(Context context) {super(context, DB_NAME, null, DB_VERSION);}/*** 這里創(chuàng)建表*/@Overridepublic void onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource) {// 創(chuàng)建表try {TableUtils.createTable(connectionSource, PackageInfo.class);TableUtils.createTable(connectionSource, Photographer.class);TableUtils.createTable(connectionSource, Theme.class);TableUtils.createTable(connectionSource, Img.class);} catch (SQLException e) {e.printStackTrace();}}/*** 這里進(jìn)行更新表操作*/@Overridepublic void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int oldVersion,int newVersion) {try { TableUtils.dropTable(connectionSource, PackageInfo.class, true); TableUtils.dropTable(connectionSource, Photographer.class, true); TableUtils.dropTable(connectionSource, Theme.class, true); TableUtils.dropTable(connectionSource, Img.class, true);onCreate(sqLiteDatabase, connectionSource); } catch (SQLException e) { e.printStackTrace(); } }/*** 通過(guò)類來(lái)獲得指定的Dao*/public synchronized Dao getDao(Class clazz) throws SQLException {Dao dao = null;String className = clazz.getSimpleName();if (daos.containsKey(className)) {dao = super.getDao(clazz);daos.put(className, dao); }return dao;}/*** 釋放資源*/@Overridepublic void close() {super.close();for (String key : daos.keySet()) {Dao dao = daos.get(key);dao = null;}}}定義實(shí)體類Bean,代表一張表
創(chuàng)建上面用到的Bean,在ormlite中,它代表數(shù)據(jù)庫(kù)中的一張表,我們所定義的所有成員變量均可為表中的字段,只要我們按照它提供的注解方式來(lái)指定成員變量屬性。
舉個(gè)栗子:
package com.devilwwj.ormlite.model;import java.io.Serializable;import com.j256.ormlite.dao.ForeignCollection; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.field.ForeignCollectionField; import com.j256.ormlite.table.DatabaseTable;/*** 套餐* @author wwj_748**/ @DatabaseTable public class PackageInfo implements Serializable{@DatabaseField(id = true)public int id;@DatabaseFieldpublic String pid;@DatabaseFieldpublic String photographerId;@DatabaseFieldpublic String name;@DatabaseField()public int cost;@DatabaseFieldpublic String description;@DatabaseFieldpublic String detail;// 一個(gè)套餐可以對(duì)應(yīng)多個(gè)主題@ForeignCollectionField(eager = true) // 必須public ForeignCollection<Theme> themes;// 外部對(duì)象,一個(gè)套餐只對(duì)應(yīng)一個(gè)攝影師,一個(gè)攝影師可以對(duì)應(yīng)多個(gè)套餐@DatabaseField(foreign = true)public Photographer photographer;@Overridepublic String toString() {return "Package [id=" + id + ", pid=" + pid + ", photographerId="+ photographerId + ", name=" + name + ", cost=" + cost+ ", description=" + description + ", detail=" + detail + "]";}}上面定義了一個(gè)套餐對(duì)象,我們來(lái)看一下它所用到的幾個(gè)注解:
@DatabaseTable:表示定義了一個(gè)數(shù)據(jù)表,如果不指定名字,在Android中會(huì)以類名作為表名,如packageInfo就是SQLite數(shù)據(jù)庫(kù)中的表名,我們也可以指定表名,@DatabaseTable(tableName = "tb_package") 。
DatabaseField:表示定義了數(shù)據(jù)中的一個(gè)字段,id表示數(shù)據(jù)中的一個(gè)主鍵,如果指定為generatedId,表示自動(dòng)增長(zhǎng)id,我們不需要給它賦值。其他字段,可以使用columnName來(lái)指定字段名,canBeNull表示是否為空,這些賦值可以按照以下來(lái)指定
-(id = true, canBeNull = false)
-
(columnName = "name")
還有更多的注解用法,可以到官網(wǎng)查看它提供的文檔,非常清楚詳盡了,筆者這里不多說(shuō)。
ormlite的外鍵約束(一對(duì)一、一對(duì)多、多對(duì)多關(guān)系)
使用這個(gè)框架需要比較注意的一點(diǎn)就是外鍵約束,這里筆者只討論一對(duì)一、一對(duì)多的情況。
上一節(jié)我們定義了PackageInfo這個(gè)實(shí)體,里面有這樣的定義:
```java
// 一個(gè)套餐可以對(duì)應(yīng)多個(gè)主題
@ForeignCollectionField(eager = true) // 必須
public ForeignCollection<Theme> themes;
我們這里不關(guān)注其他字段,關(guān)注它的外鍵字段,前面我們說(shuō)到,一個(gè)套餐對(duì)應(yīng)多個(gè)主題,所以我們?cè)谥黝}這個(gè)實(shí)體類中也需要定義一個(gè)關(guān)聯(lián)套餐的字段。
// 外部對(duì)象字段@DatabaseField(foreign = true, foreignAutoRefresh = true)public PackageInfo mPackage;注:要實(shí)現(xiàn)一對(duì)多關(guān)系,一定要這樣定義,不然會(huì)出錯(cuò)。
定義Bean的DAO,對(duì)數(shù)據(jù)庫(kù)進(jìn)行增、刪、改、查
這里筆者舉個(gè)例子,大家以后開發(fā)根據(jù)這樣來(lái)添加相應(yīng)的業(yè)務(wù)邏輯方法:
package com.devilwwj.ormlite.dao;import java.sql.SQLException; import java.util.ArrayList; import java.util.List;import android.content.Context;import com.devilwwj.ormlite.db.DBHelper; import com.devilwwj.ormlite.model.Theme; import com.j256.ormlite.dao.Dao;/*** 定義數(shù)據(jù)訪問(wèn)對(duì)象,對(duì)指定的表進(jìn)行增刪改查操作* @author devilwwj**/ public class ThemeDao {private Dao<Theme, Integer> themeDao;private DBHelper dbHelper;/*** 構(gòu)造方法* 獲得數(shù)據(jù)庫(kù)幫助類實(shí)例,通過(guò)傳入Class對(duì)象得到相應(yīng)的Dao* @param context*/public ThemeDao(Context context) {try {dbHelper = DBHelper.getHelper(context);themeDao = dbHelper.getDao(Theme.class);} catch (SQLException e) {e.printStackTrace();}}/*** 添加一條記錄* @param theme*/public void add(Theme theme) {try {themeDao.create(theme);} catch (SQLException e) {e.printStackTrace();}}/*** 刪除一條記錄* @param theme*/public void delete(Theme theme) {try {themeDao.delete(theme);} catch (SQLException e) {e.printStackTrace();}}/*** 更新一條記錄* @param theme*/public void update(Theme theme) {try {themeDao.update(theme);} catch (SQLException e) {e.printStackTrace();}}/*** 查詢一條記錄* @param id* @return*/public Theme queryForId(int id) {Theme theme = null;try {theme = themeDao.queryForId(id);} catch (SQLException e) {e.printStackTrace();}return theme;}/*** 查詢所有記錄* @return*/public List<Theme> queryForAll() {List<Theme> themes = new ArrayList<Theme>();try {themes = themeDao.queryForAll();} catch (SQLException e) {e.printStackTrace();}return themes;}}上面筆者定義了一個(gè)Dao類,用來(lái)進(jìn)行數(shù)據(jù)訪問(wèn)的,定義了增加、刪除、更新、查詢幾個(gè)方法,我們?cè)趹?yīng)用中就可以使用這個(gè)幾個(gè)方法來(lái)幫助我們完成相關(guān)的操作。
具體使用方法:
Theme theme = new Theme(); // 賦值 theme.id = 1; theme.title = "主題"; theme.detail = "主題詳情"; new ThemeDao(context).add(theme);ormlite的批處理操作
/*** 轉(zhuǎn)化json對(duì)象為數(shù)據(jù)庫(kù)對(duì)象* @param context* @param theme* @return* @throws SQLException* @throws Exception*/public static Theme ConvertTheme(Context context, final JSONObject theme) throws SQLException, Exception {JSONObject photographerObj = theme.getJSONObject("photographer");JSONObject packageObj = theme.getJSONObject("package");ThemeDao themeDao = new ThemeDao(context);PhotographDao photographDao = new PhotographDao(context);// 根據(jù)id查詢攝影師Photographer mPhotographer = photographDao.queryForId(theme.optInt("photographerId"));if (mPhotographer == null)mPhotographer = new Photographer();mPhotographer.id = theme.optString("photographerId");mPhotographer.name = photographerObj.optString("nickname");mPhotographer.serviceArea = photographerObj.optString("serviceArea");mPhotographer.avatar = photographerObj.optString("avatar");// 這里創(chuàng)建或更新攝影師photographDao.createOrUpdate(mPhotographer);PackageDao packageDao = new PackageDao(context);// 根據(jù)id查詢套餐PackageInfo mPackage = packageDao.queryForId(packageObj.optInt("id"));if (mPackage == null) mPackage = new PackageInfo();mPackage.id = packageObj.optInt("id");mPackage.name = packageObj.optString("title");mPackage.cost = packageObj.optInt("cost");mPackage.detail = packageObj.optString("detail");// 這里創(chuàng)建或更新套餐packageDao.createOrUpdate(mPackage);// 根據(jù)id查詢作品Theme mThemeTmp = themeDao.queryForId(theme.optInt("id"));if (mThemeTmp == null)mThemeTmp = new Theme(); final Theme mTheme = mThemeTmp;mTheme.id = theme.optString("id");mTheme.title = theme.optString("title");// mTheme.coverId = theme.optString("place");// mTheme.coverUrl = theme.optString("coverUrl");mTheme.photographerId = theme.optString("photographerId");mTheme.detail = theme.optString("detail");// mTheme.cost = theme.optDouble("cost");// mTheme.recordTime = theme.optString("recordTime");mTheme.favStatus = theme.optInt("isFav");mTheme.photoCount = theme.optInt("photoCount");mTheme.tags = theme.optString("tags");mTheme.packageId = theme.optString("packageId");// 同步更新mTheme.photographer = mPhotographer;mTheme.mPackage = mPackage;// 創(chuàng)建或更新主題themeDao.createOrUpdate(mTheme);final ImgDao mDao = new ImgDao(context);Dao<Img, Integer> imgDao = mDao.getImgDao();// 執(zhí)行批處理操作imgDao.callBatchTasks(new Callable<Void>() {@Overridepublic Void call() throws Exception {JSONArray imgs = theme.getJSONArray("photos");for (int i = 0; i < imgs.length(); i++) {JSONObject jsonObject = imgs.getJSONObject(i);Img mImg = mDao.queryForId(jsonObject.optInt("id"));if (mImg == null)mImg = new Img();mImg.id = jsonObject.optString("id");mImg.isCover = jsonObject.optInt("isCover");mImg.imgUrl = jsonObject.optString("url");mImg.theme = mTheme;mDao.createOrUpdate(mImg);}return null;}});return mTheme;}上面的代碼就是把我們從服務(wù)端獲取的json對(duì)象進(jìn)行數(shù)據(jù)轉(zhuǎn)化,我們對(duì)json數(shù)據(jù)進(jìn)行解析,得到相應(yīng)的數(shù)據(jù)庫(kù)對(duì)象,再進(jìn)行創(chuàng)建或更新的操作,如果涉及到較多的插入,就可以使用ormlite為我們提供的批處理回調(diào)方法,具體看代碼。
在Android中使用
我們通過(guò)網(wǎng)絡(luò)請(qǐng)求得到的json對(duì)象,然后直接調(diào)用上面寫好的轉(zhuǎn)化方法,這樣我們就可以實(shí)現(xiàn)數(shù)據(jù)存儲(chǔ)了。
private void getTheme(final Theme mTheme) {DataFetcher.getHttpRequestAsync(HttpRequest.getThemeInfoUrl(getActivity(), mTheme.id),new JsonResponseHandler(getActivity(),getString(R.string.tip_requesing_info)) {@Overridepublic void onSuccess(int statusCode, Header[] headers,JSONObject response) {super.onSuccess(statusCode, headers, response);LogUtils.i("info", response.toString());JSONObject jsonObject = response.optJSONObject("msg");try {Converter.ConvertTheme(jsonObject,((BaseActivity) getActivity()).getHelper());// 跳轉(zhuǎn)到詳情頁(yè)Intent intent = new Intent();intent.putExtra("tid", mTheme.id);intent.setClass(getActivity(),ThemeInfolActivity.class);startActivity(intent);} catch (Exception e) {e.printStackTrace();}}@Overridepublic void onFailure(int statusCode, Header[] headers,String responseString, Throwable throwable) {super.onFailure(statusCode, headers, responseString,throwable);if (mTheme.detail != null) {Intent intent = new Intent();intent.putExtra("tid", mTheme.id);intent.setClass(getActivity(), ThemeInfolActivity.class);startActivity(intent);} else {Toast.makeText(getActivity(), responseString,Toast.LENGTH_SHORT).show();}}});}注:這里筆者使用的是android-async-http這個(gè)網(wǎng)絡(luò)庫(kù)。
總結(jié)
以上是生活随笔為你收集整理的Android 数据库框架ormlite 使用精要的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Java相对路径读取文件
- 下一篇: Hadoop API编程——FileSy