Android 数据库框架ormlite 使用精要
Android 數據庫框架ormlite 使用精要
前言
本篇博客記錄一下筆者在實際開發中使用到的一個數據庫框架,這個可以讓我們快速實現數據庫操作,避免頻繁手寫sql,提高我們的開發效率,減少出錯的機率。
ormlite是什么?
首先可以去它的官網看看www.ormlite.com,它的英文全稱是Object Relational Mapping,意思是對象關系映射;如果接觸過Java EE開發的,一定知道Java Web開發就有一個類似的數據庫映射框架——Hibernate。簡單來說,就是我們定義一個實體類,利用這個框架,它可以幫我們吧這個實體映射到我們的數據庫中,在Android中是SQLite,數據中的字段就是我們定義實體的成員變量。
為什么要用ormlite?
先說說優點
缺點
如何使用?
導入jar包到項目libs文件夾下
到http://ormlite.com/releases/下載相應版本的jar,下載最新的,目前是最新版本4.49。我們下載穩定的4.48即可。
繼承OrmLiteSqliteOpenHelper類定義數據庫幫助類
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;/*** 功能:數據庫幫助類* @author devilwwj**/ public class DBHelper extends OrmLiteSqliteOpenHelper {/*** 數據庫名字*/private static final String DB_NAME = "test.db";/*** 數據庫版本*/private static final int DB_VERSION = 1;/*** 用來存放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;}/*** 構造方法* @param context*/public DBHelper(Context context) {super(context, DB_NAME, null, DB_VERSION);}/*** 這里創建表*/@Overridepublic void onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource) {// 創建表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();}}/*** 這里進行更新表操作*/@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(); } }/*** 通過類來獲得指定的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;}}}定義實體類Bean,代表一張表
創建上面用到的Bean,在ormlite中,它代表數據庫中的一張表,我們所定義的所有成員變量均可為表中的字段,只要我們按照它提供的注解方式來指定成員變量屬性。
舉個栗子:
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;// 一個套餐可以對應多個主題@ForeignCollectionField(eager = true) // 必須public ForeignCollection<Theme> themes;// 外部對象,一個套餐只對應一個攝影師,一個攝影師可以對應多個套餐@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 + "]";}}上面定義了一個套餐對象,我們來看一下它所用到的幾個注解:
@DatabaseTable:表示定義了一個數據表,如果不指定名字,在Android中會以類名作為表名,如packageInfo就是SQLite數據庫中的表名,我們也可以指定表名,@DatabaseTable(tableName = "tb_package") 。
DatabaseField:表示定義了數據中的一個字段,id表示數據中的一個主鍵,如果指定為generatedId,表示自動增長id,我們不需要給它賦值。其他字段,可以使用columnName來指定字段名,canBeNull表示是否為空,這些賦值可以按照以下來指定
-(id = true, canBeNull = false)
-
(columnName = "name")
還有更多的注解用法,可以到官網查看它提供的文檔,非常清楚詳盡了,筆者這里不多說。
ormlite的外鍵約束(一對一、一對多、多對多關系)
使用這個框架需要比較注意的一點就是外鍵約束,這里筆者只討論一對一、一對多的情況。
上一節我們定義了PackageInfo這個實體,里面有這樣的定義:
```java
// 一個套餐可以對應多個主題
@ForeignCollectionField(eager = true) // 必須
public ForeignCollection<Theme> themes;
我們這里不關注其他字段,關注它的外鍵字段,前面我們說到,一個套餐對應多個主題,所以我們在主題這個實體類中也需要定義一個關聯套餐的字段。
// 外部對象字段@DatabaseField(foreign = true, foreignAutoRefresh = true)public PackageInfo mPackage;注:要實現一對多關系,一定要這樣定義,不然會出錯。
定義Bean的DAO,對數據庫進行增、刪、改、查
這里筆者舉個例子,大家以后開發根據這樣來添加相應的業務邏輯方法:
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;/*** 定義數據訪問對象,對指定的表進行增刪改查操作* @author devilwwj**/ public class ThemeDao {private Dao<Theme, Integer> themeDao;private DBHelper dbHelper;/*** 構造方法* 獲得數據庫幫助類實例,通過傳入Class對象得到相應的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;}}上面筆者定義了一個Dao類,用來進行數據訪問的,定義了增加、刪除、更新、查詢幾個方法,我們在應用中就可以使用這個幾個方法來幫助我們完成相關的操作。
具體使用方法:
Theme theme = new Theme(); // 賦值 theme.id = 1; theme.title = "主題"; theme.detail = "主題詳情"; new ThemeDao(context).add(theme);ormlite的批處理操作
/*** 轉化json對象為數據庫對象* @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);// 根據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");// 這里創建或更新攝影師photographDao.createOrUpdate(mPhotographer);PackageDao packageDao = new PackageDao(context);// 根據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");// 這里創建或更新套餐packageDao.createOrUpdate(mPackage);// 根據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;// 創建或更新主題themeDao.createOrUpdate(mTheme);final ImgDao mDao = new ImgDao(context);Dao<Img, Integer> imgDao = mDao.getImgDao();// 執行批處理操作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;}上面的代碼就是把我們從服務端獲取的json對象進行數據轉化,我們對json數據進行解析,得到相應的數據庫對象,再進行創建或更新的操作,如果涉及到較多的插入,就可以使用ormlite為我們提供的批處理回調方法,具體看代碼。
在Android中使用
我們通過網絡請求得到的json對象,然后直接調用上面寫好的轉化方法,這樣我們就可以實現數據存儲了。
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());// 跳轉到詳情頁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這個網絡庫。
總結
以上是生活随笔為你收集整理的Android 数据库框架ormlite 使用精要的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java相对路径读取文件
- 下一篇: Hadoop API编程——FileSy