您的位置:首页 > 移动开发 > Android开发

开源框架-ormlite-android数据库的使用

2015-08-28 23:50 603 查看
首先说明一下,本人已经使用ormlite-android做过两个大型的项目开发,很久以来就想对此数据库做一些总结,正好今天有空就写出来:

1. 首先去官网http://ormlite.com/看官方说明,也可以去http://ormlite.com/releases/下载两个包:一个是ormlite-core-4.24.jar,另一个是ormlite-android-4.24.jar

2. 下载完2个jar包后导入项目中,在此不多说,大家都懂的

3.前奏工作完成,下面就是怎么去搭建框架使用了,首先说明本人做过一段时间的web开发,所以喜欢用mvc模式,下面将通过代码来说明:

1).建立自己的DatabaseHelper类

[java] view
plaincopy





public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

// name of the database file for your application -- change to something

// appropriate for your app

private static final String DATABASE_NAME = "CHENGYIJI.db";

// any time you make changes to your database objects, you may have to

// increase the database version

private static final int DATABASE_VERSION = 1;

// the DAO object we use to access the SimpleData table

//数据库默认路径SDCard

[java] view
plaincopy





private static String DATABASE_PATH = Environment.getExternalStorageDirectory()

+ "/CHENGYIJI.db";

private Context mContext;

[java] view
plaincopy





//数据库配置文件默认路径SDCard

[java] view
plaincopy





private static String DATABASE_PATH_JOURN = Environment.getExternalStorageDirectory()

+ "/CHEYIJI.db-journal";

public DatabaseHelper(Context context) {

super(context, DATABASE_NAME, null, DATABASE_VERSION);

mContext = context;

initDtaBasePath();

try {

File f = new File(DATABASE_PATH);

if (!f.exists()) {

SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(DATABASE_PATH, null);

onCreate(db);

db.close();

}

} catch (Exception e) {

}

}

[java] view
plaincopy





//如果没有SDCard 默认存储在项目文件目录下

[java] view
plaincopy





private void initDtaBasePath() {

if (!Utils.ExistSDCard()) {

DATABASE_PATH = mContext.getFilesDir().getAbsolutePath() + "/CHENGYIJI.db";

DATABASE_PATH_JOURN = mContext.getFilesDir().getAbsolutePath() + "/CHEYIJI.db-journal";

}

}

@Override

public synchronized SQLiteDatabase getWritableDatabase() {

return SQLiteDatabase.openDatabase(DATABASE_PATH, null, SQLiteDatabase.OPEN_READWRITE);

}

public synchronized SQLiteDatabase getReadableDatabase() {

return SQLiteDatabase.openDatabase(DATABASE_PATH, null, SQLiteDatabase.OPEN_READONLY);

}

/**

* This is called when the database is first created. Usually you should

* call createTable statements here to create the tables that will store

* your data.

*/

@Override

public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {

LogTool.i(DatabaseHelper.class.getName(), "onCreate");

try {

TableUtils.createTable(connectionSource, UserInfo.class);

} catch (java.sql.SQLException e) {

LogTool.e(DatabaseHelper.class.getName(), "Can't create database", e);

throw new RuntimeException(e);

}

}

/**

* This is called when your application is upgraded and it has a higher

* version number. This allows you to adjust the various data to match the

* new version number.

*/

@Override

public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion,

int newVersion) {

LogTool.i(DatabaseHelper.class.getName(), "onUpgrade");

try {

TableUtils.dropTable(connectionSource, UserInfo.class, true);

onCreate(db, connectionSource);

} catch (java.sql.SQLException e) {

LogTool.e(DatabaseHelper.class.getName(), "Can't drop databases", e);

throw new RuntimeException(e);

}

}

public void deleteDB() {

if (mContext != null) {

File f = mContext.getDatabasePath(DATABASE_NAME);

if (f.exists()) {

// mContext.deleteDatabase(DATABASE_NAME);

LogTool.e("DB", "---delete SDCard DB---");

f.delete();

} else {

LogTool.e("DB", "---delete App DB---");

mContext.deleteDatabase(DATABASE_NAME);

}

File file = mContext.getDatabasePath(DATABASE_PATH);

if (file.exists()) {

LogTool.e("DB", "---delete SDCard DB 222---");

file.delete();

}

File file2 = mContext.getDatabasePath(DATABASE_PATH_JOURN);

if (file2.exists()) {

LogTool.e("DB", "---delete SDCard DB 333---");

file2.delete();

}

}

}

/**

* Close the database connections and clear any cached DAOs.

*/

@Override

public void close() {

super.close();

}

[java] view
plaincopy





[java] view
plaincopy





2)创建自己的数据库操作Dao层】

[java] view
plaincopy





<pre code_snippet_id="259903" snippet_file_name="blog_20140327_9_7716430" class="java" name="code">public abstract class BaseDao<T, Integer> {

protected DatabaseHelper mDatabaseHelper;

protected Context mContext;

public BaseDao(Context context) {

mContext = context;

getHelper();

}

public DatabaseHelper getHelper() {

if (mDatabaseHelper == null) {

mDatabaseHelper = OpenHelperManager.getHelper(mContext, DatabaseHelper.class);

}

return mDatabaseHelper;

}

public abstract Dao<T, Integer> getDao() throws SQLException;

public int save(T t) throws SQLException {

return getDao().create(t);

}

public List<T> query(PreparedQuery<T> preparedQuery) throws SQLException {

Dao<T, Integer> dao = getDao();

return dao.query(preparedQuery);

}

public List<T> query(String attributeName, String attributeValue) throws SQLException {

QueryBuilder<T, Integer> queryBuilder = getDao().queryBuilder();

queryBuilder.where().eq(attributeName, attributeValue);

PreparedQuery<T> preparedQuery = queryBuilder.prepare();

return query(preparedQuery);

}

public List<T> query(String[] attributeNames, String[] attributeValues) throws SQLException,

InvalidParamsException {

if (attributeNames.length != attributeValues.length) {

throw new InvalidParamsException("params size is not equal");

}

QueryBuilder<T, Integer> queryBuilder = getDao().queryBuilder();

Where<T, Integer> wheres = queryBuilder.where();

for (int i = 0; i < attributeNames.length; i++) {

wheres.eq(attributeNames[i], attributeValues[i]);

}

PreparedQuery<T> preparedQuery = queryBuilder.prepare();

return query(preparedQuery);

}

public List<T> queryAll() throws SQLException {

// QueryBuilder<T, Integer> queryBuilder = getDao().queryBuilder();

// PreparedQuery<T> preparedQuery = queryBuilder.prepare();

// return query(preparedQuery);

Dao<T, Integer> dao = getDao();

return dao.queryForAll();

}

public T queryById(String idName, String idValue) throws SQLException {

List<T> lst = query(idName, idValue);

if (null != lst && !lst.isEmpty()) {

return lst.get(0);

} else {

return null;

}

}

public int delete(PreparedDelete<T> preparedDelete) throws SQLException {

Dao<T, Integer> dao = getDao();

return dao.delete(preparedDelete);

}

public int delete(T t) throws SQLException {

Dao<T, Integer> dao = getDao();

return dao.delete(t);

}

public int delete(List<T> lst) throws SQLException {

Dao<T, Integer> dao = getDao();

return dao.delete(lst);

}

public int delete(String[] attributeNames, String[] attributeValues) throws SQLException,

InvalidParamsException {

List<T> lst = query(attributeNames, attributeValues);

if (null != lst && !lst.isEmpty()) {

return delete(lst);

}

return 0;

}

public int deleteById(String idName, String idValue) throws SQLException,

InvalidParamsException {

T t = queryById(idName, idValue);

if (null != t) {

return delete(t);

}

return 0;

}

public int update(T t) throws SQLException {

Dao<T, Integer> dao = getDao();

return dao.update(t);

}

public boolean isTableExsits() throws SQLException {

return getDao().isTableExists();

}

public long countOf() throws SQLException {

return getDao().countOf();

}

public List<T> query(Map<String, Object> map) throws SQLException {

QueryBuilder<T, Integer> queryBuilder = getDao().queryBuilder();

if (!map.isEmpty()) {

Where<T, Integer> wheres = queryBuilder.where();

Set<String> keys = map.keySet();

ArrayList<String> keyss = new ArrayList<String>();

keyss.addAll(keys);

for (int i = 0; i < keyss.size(); i++) {

if (i == 0) {

wheres.eq(keyss.get(i), map.get(keyss.get(i)));

} else {

wheres.and().eq(keyss.get(i), map.get(keyss.get(i)));

}

}

}

PreparedQuery<T> preparedQuery = queryBuilder.prepare();

return query(preparedQuery);

}

public List<T> query(Map<String, Object> map, Map<String, Object> lowMap,

Map<String, Object> highMap) throws SQLException {

QueryBuilder<T, Integer> queryBuilder = getDao().queryBuilder();

Where<T, Integer> wheres = queryBuilder.where();

if (!map.isEmpty()) {

Set<String> keys = map.keySet();

ArrayList<String> keyss = new ArrayList<String>();

keyss.addAll(keys);

for (int i = 0; i < keyss.size(); i++) {

if (i == 0) {

wheres.eq(keyss.get(i), map.get(keyss.get(i)));

} else {

wheres.and().eq(keyss.get(i), map.get(keyss.get(i)));

}

}

}

if (!lowMap.isEmpty()) {

Set<String> keys = lowMap.keySet();

ArrayList<String> keyss = new ArrayList<String>();

keyss.addAll(keys);

for (int i = 0; i < keyss.size(); i++) {

if(map.isEmpty()){

wheres.gt(keyss.get(i), lowMap.get(keyss.get(i)));

}else{

wheres.and().gt(keyss.get(i), lowMap.get(keyss.get(i)));

}

}

}

if (!highMap.isEmpty()) {

Set<String> keys = highMap.keySet();

ArrayList<String> keyss = new ArrayList<String>();

keyss.addAll(keys);

for (int i = 0; i < keyss.size(); i++) {

wheres.and().lt(keyss.get(i), highMap.get(keyss.get(i)));

}

}

PreparedQuery<T> preparedQuery = queryBuilder.prepare();

return query(preparedQuery);

}

}</pre><br>

3)怎么应用

<pre></pre>

<pre code_snippet_id="259903" snippet_file_name="blog_20140327_10_1652362" class="java" name="code">首先有一个model对象</pre><pre code_snippet_id="259903" snippet_file_name="blog_20140327_11_6908852" class="java" name="code"><p>public class CashFlow implements ICashFlowRecorder, Serializable {

/**

*

*/

private static final long serialVersionUID = 1L;</p><p> // 流水号ID

@DatabaseField(generatedId = true, columnName = "cash_flow_id")

private long cashFlowId;</p><p> // 类型:0收,1支

@DatabaseField(canBeNull = false, columnName = "type")

private int type;</p><p> // 资金类型 - 0 贷款,1借款,2货款,3其他

@DatabaseField(canBeNull = false, columnName = "cash_type")

private int cashType;</p><p> // 资金类型为其他是的 描述

@DatabaseField(columnName = "other_type_desc")

private String otherTypeDesc;</p><p> // 是否参与核销:0否,1是

@DatabaseField(canBeNull = false, columnName = "write_off_flag")

private int writeOffFlag;</p><p> // 关联用户ID

// private long referUserId;

@DatabaseField(foreign = true, foreignAutoRefresh = true, columnName = "phone_book_id")

private PhoneBook referUser;</p><p> // 资金

@DatabaseField(canBeNull = false, columnName = "amount")

private double amount;</p><p> // 登记日期

@DatabaseField(canBeNull = false, columnName = "reg_date")

private long regDate;</p><p> // 创建时间

@DatabaseField(canBeNull = false, columnName = "create_date")

private long createDate;</p><p> // 修改时间

@DatabaseField(canBeNull = false, columnName = "update_date")

private long updateDate;</p><p> // 关联账单ID

@DatabaseField(foreign = true, foreignAutoRefresh = true, columnName = "bill_id")

private Bill referBill;</p><p> public long getCashFlowId() {

return cashFlowId;

}</p><p> public void setCashFlowId(long cashFlowId) {

this.cashFlowId = cashFlowId;

}</p><p> public int getType() {

return type;

}</p><p> public void setType(int type) {

this.type = type;

}</p><p> public int getCashType() {

return cashType;

}</p><p> public void setCashType(int cashType) {

this.cashType = cashType;

}</p><p> public String getOtherTypeDesc() {

return otherTypeDesc;

}</p><p> public void setOtherTypeDesc(String otherTypeDesc) {

this.otherTypeDesc = otherTypeDesc;

}</p><p> public int getWriteOffFlag() {

return writeOffFlag;

}</p><p> public void setWriteOffFlag(int writeOffFlag) {

this.writeOffFlag = writeOffFlag;

}</p><p> public PhoneBook getReferUser() {

return referUser;

}</p><p> public void setReferUser(PhoneBook referUser) {

this.referUser = referUser;

}</p><p> public double getAmount() {

return amount;

}</p><p> public void setAmount(double amount) {

this.amount = amount;

}</p><p> public long getRegDate() {

return regDate;

}</p><p> public void setRegDate(long regDate) {

this.regDate = regDate;

}</p><p> public long getCreateDate() {

return createDate;

}</p><p> public void setCreateDate(long createDate) {

this.createDate = createDate;

}</p><p> public long getUpdateDate() {

return updateDate;

}</p><p> public void setUpdateDate(long updateDate) {

this.updateDate = updateDate;

}</p><p> public Bill getReferBill() {

return referBill;

}</p><p> public void setReferBill(Bill referBill) {

this.referBill = referBill;

}</p><p>}</p></pre><pre code_snippet_id="259903" snippet_file_name="blog_20140327_12_2306263" class="java" name="code">然后建立自己的dao</pre><pre code_snippet_id="259903" snippet_file_name="blog_20140327_13_1499468" class="java" name="code"><p>public class CashFlowDao extends BaseDao<CashFlow, Integer> {</p><p> public CashFlowDao(Context context) {

super(context);

}</p><p> @Override

public Dao<CashFlow, Integer> getDao() throws SQLException {

return getHelper().getDao(CashFlow.class);

}</p><p>}</p></pre><pre code_snippet_id="259903" snippet_file_name="blog_20140327_14_7071602" class="java" name="code">最后应用dao,查询某一段时间内的CashFlow</pre><pre code_snippet_id="259903" snippet_file_name="blog_20140327_15_5675379" class="java" name="code"> @SuppressWarnings("deprecation")

private void queCashFlow(int msgType, long lowTime, long highTime) {

try {

CashFlowDao cashFlowDao = new CashFlowDao(this);

Map<String, Object> map = new HashMap<String, Object>();

Map<String, Object> lowMap = new HashMap<String, Object>();

lowMap.put("create_date", lowTime);

Map<String, Object> highMap = new HashMap<String, Object>();

highMap.put("create_date", highTime);

ArrayList<CashFlow> cashFlows = (ArrayList<CashFlow>)cashFlowDao.query(map, lowMap,

highMap);

if (cashFlows != null && cashFlows.size() > 0) {

Message message = new Message();

message.what = msgType;

message.obj = cashFlows;

handler.sendMessage(message);

} else {

handler.sendEmptyMessage(4);

}

} catch (SQLException e) {

handler.sendEmptyMessage(4);

}

}</pre><pre code_snippet_id="259903" snippet_file_name="blog_20140327_17_2043902" class="java" name="code"> </pre><pre code_snippet_id="259903" snippet_file_name="blog_20140327_17_2043902" class="java" name="code"> </pre>

<p><br>

</p>

<div style="padding-top:20px">

<p style="font-size:12px;">版权声明:本文为博主原创文章,未经博主允许不得转载。</p>

</div>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: