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

首先说明一下,本人已经使用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 plain copy 在CODE上查看代码片 派生到我的代码片
  1. public class DatabaseHelper extends OrmLiteSqliteOpenHelper {  
  2.   
  3.     // name of the database file for your application -- change to something  
  4.     // appropriate for your app  
  5.     private static final String DATABASE_NAME = "CHENGYIJI.db";  
  6.   
  7.     // any time you make changes to your database objects, you may have to  
  8.     // increase the database version  
  9.     private static final int DATABASE_VERSION = 1;  
  10.   
  11.     // the DAO object we use to access the SimpleData table  
  12.   
  13.     //数据库默认路径SDCard  
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. private static String DATABASE_PATH = Environment.getExternalStorageDirectory()  
  2.         + "/CHENGYIJI.db";  
  3.   
  4. private Context mContext;  
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //数据库配置文件默认路径SDCard  
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. private static String DATABASE_PATH_JOURN = Environment.getExternalStorageDirectory()  
  2.         + "/CHEYIJI.db-journal";  
  3.   
  4.   
  5. public DatabaseHelper(Context context) {  
  6.     super(context, DATABASE_NAME, null, DATABASE_VERSION);  
  7.     mContext = context;  
  8.     initDtaBasePath();  
  9.     try {  
  10.   
  11.         File f = new File(DATABASE_PATH);  
  12.         if (!f.exists()) {  
  13.             SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(DATABASE_PATH, null);  
  14.             onCreate(db);  
  15.             db.close();  
  16.         }  
  17.     } catch (Exception e) {  
  18.     }  
  19. }  
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //如果没有SDCard 默认存储在项目文件目录下  
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. private void initDtaBasePath() {  
  2.     if (!Utils.ExistSDCard()) {  
  3.         DATABASE_PATH = mContext.getFilesDir().getAbsolutePath() + "/CHENGYIJI.db";  
  4.         DATABASE_PATH_JOURN = mContext.getFilesDir().getAbsolutePath() + "/CHEYIJI.db-journal";  
  5.     }  
  6. }  
  7.   
  8. @Override  
  9. public synchronized SQLiteDatabase getWritableDatabase() {  
  10.     return SQLiteDatabase.openDatabase(DATABASE_PATH, null, SQLiteDatabase.OPEN_READWRITE);  
  11. }  
  12.   
  13. public synchronized SQLiteDatabase getReadableDatabase() {  
  14.     return SQLiteDatabase.openDatabase(DATABASE_PATH, null, SQLiteDatabase.OPEN_READONLY);  
  15. }  
  16.   
  17. /** 
  18.  * This is called when the database is first created. Usually you should 
  19.  * call createTable statements here to create the tables that will store 
  20.  * your data. 
  21.  */  
  22. @Override  
  23. public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {  
  24.     LogTool.i(DatabaseHelper.class.getName(), "onCreate");  
  25.     try {  
  26.         TableUtils.createTable(connectionSource, UserInfo.class);  
  27.     } catch (java.sql.SQLException e) {  
  28.         LogTool.e(DatabaseHelper.class.getName(), "Can't create database", e);  
  29.         throw new RuntimeException(e);  
  30.     }  
  31.   
  32. }  
  33.   
  34. /** 
  35.  * This is called when your application is upgraded and it has a higher 
  36.  * version number. This allows you to adjust the various data to match the 
  37.  * new version number. 
  38.  */  
  39. @Override  
  40. public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion,  
  41.         int newVersion) {  
  42.     LogTool.i(DatabaseHelper.class.getName(), "onUpgrade");  
  43.     try {  
  44.         TableUtils.dropTable(connectionSource, UserInfo.classtrue);  
  45.         onCreate(db, connectionSource);  
  46.     } catch (java.sql.SQLException e) {  
  47.         LogTool.e(DatabaseHelper.class.getName(), "Can't drop databases", e);  
  48.         throw new RuntimeException(e);  
  49.     }  
  50. }  
  51.   
  52.   
  53. public void deleteDB() {  
  54.     if (mContext != null) {  
  55.         File f = mContext.getDatabasePath(DATABASE_NAME);  
  56.         if (f.exists()) {  
  57.             // mContext.deleteDatabase(DATABASE_NAME);  
  58.             LogTool.e("DB""---delete SDCard DB---");  
  59.             f.delete();  
  60.         } else {  
  61.             LogTool.e("DB""---delete App DB---");  
  62.             mContext.deleteDatabase(DATABASE_NAME);  
  63.         }  
  64.   
  65.         File file = mContext.getDatabasePath(DATABASE_PATH);  
  66.         if (file.exists()) {  
  67.             LogTool.e("DB""---delete SDCard DB 222---");  
  68.             file.delete();  
  69.         }  
  70.   
  71.         File file2 = mContext.getDatabasePath(DATABASE_PATH_JOURN);  
  72.         if (file2.exists()) {  
  73.             LogTool.e("DB""---delete SDCard DB 333---");  
  74.             file2.delete();  
  75.         }  
  76.     }  
  77. }  
  78.   
  79. /** 
  80.  * Close the database connections and clear any cached DAOs. 
  81.  */  
  82. @Override  
  83. public void close() {  
  84.     super.close();  
  85. }  
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1.    
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. 2)创建自己的数据库操作Dao层】  
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <pre code_snippet_id="259903" snippet_file_name="blog_20140327_9_7716430" class="java" name="code">public abstract class BaseDao<T, Integer> {  
  2.     protected DatabaseHelper mDatabaseHelper;  
  3.   
  4.     protected Context mContext;  
  5.   
  6.     public BaseDao(Context context) {  
  7.         mContext = context;  
  8.         getHelper();  
  9.     }  
  10.   
  11.     public DatabaseHelper getHelper() {  
  12.         if (mDatabaseHelper == null) {  
  13.             mDatabaseHelper = OpenHelperManager.getHelper(mContext, DatabaseHelper.class);  
  14.         }  
  15.         return mDatabaseHelper;  
  16.     }  
  17.   
  18.     public abstract Dao<T, Integer> getDao() throws SQLException;  
  19.   
  20.     public int save(T t) throws SQLException {  
  21.         return getDao().create(t);  
  22.     }  
  23.   
  24.     public List<T> query(PreparedQuery<T> preparedQuery) throws SQLException {  
  25.         Dao<T, Integer> dao = getDao();  
  26.         return dao.query(preparedQuery);  
  27.     }  
  28.   
  29.     public List<T> query(String attributeName, String attributeValue) throws SQLException {  
  30.         QueryBuilder<T, Integer> queryBuilder = getDao().queryBuilder();  
  31.         queryBuilder.where().eq(attributeName, attributeValue);  
  32.         PreparedQuery<T> preparedQuery = queryBuilder.prepare();  
  33.         return query(preparedQuery);  
  34.     }  
  35.   
  36.     public List<T> query(String[] attributeNames, String[] attributeValues) throws SQLException,  
  37.             InvalidParamsException {  
  38.         if (attributeNames.length != attributeValues.length) {  
  39.             throw new InvalidParamsException("params size is not equal");  
  40.         }  
  41.         QueryBuilder<T, Integer> queryBuilder = getDao().queryBuilder();  
  42.         Where<T, Integer> wheres = queryBuilder.where();  
  43.         for (int i = 0; i < attributeNames.length; i++) {  
  44.             wheres.eq(attributeNames[i], attributeValues[i]);  
  45.         }  
  46.         PreparedQuery<T> preparedQuery = queryBuilder.prepare();  
  47.         return query(preparedQuery);  
  48.     }  
  49.   
  50.     public List<T> queryAll() throws SQLException {  
  51.         // QueryBuilder<T, Integer> queryBuilder = getDao().queryBuilder();  
  52.         // PreparedQuery<T> preparedQuery = queryBuilder.prepare();  
  53.         // return query(preparedQuery);  
  54.         Dao<T, Integer> dao = getDao();  
  55.         return dao.queryForAll();  
  56.     }  
  57.   
  58.     public T queryById(String idName, String idValue) throws SQLException {  
  59.         List<T> lst = query(idName, idValue);  
  60.         if (null != lst && !lst.isEmpty()) {  
  61.             return lst.get(0);  
  62.         } else {  
  63.             return null;  
  64.         }  
  65.     }  
  66.   
  67.     public int delete(PreparedDelete<T> preparedDelete) throws SQLException {  
  68.         Dao<T, Integer> dao = getDao();  
  69.         return dao.delete(preparedDelete);  
  70.     }  
  71.   
  72.     public int delete(T t) throws SQLException {  
  73.         Dao<T, Integer> dao = getDao();  
  74.         return dao.delete(t);  
  75.     }  
  76.   
  77.     public int delete(List<T> lst) throws SQLException {  
  78.         Dao<T, Integer> dao = getDao();  
  79.         return dao.delete(lst);  
  80.     }  
  81.   
  82.     public int delete(String[] attributeNames, String[] attributeValues) throws SQLException,  
  83.             InvalidParamsException {  
  84.         List<T> lst = query(attributeNames, attributeValues);  
  85.         if (null != lst && !lst.isEmpty()) {  
  86.             return delete(lst);  
  87.         }  
  88.         return 0;  
  89.     }  
  90.   
  91.     public int deleteById(String idName, String idValue) throws SQLException,  
  92.             InvalidParamsException {  
  93.         T t = queryById(idName, idValue);  
  94.         if (null != t) {  
  95.             return delete(t);  
  96.         }  
  97.         return 0;  
  98.     }  
  99.   
  100.     public int update(T t) throws SQLException {  
  101.         Dao<T, Integer> dao = getDao();  
  102.         return dao.update(t);  
  103.     }  
  104.   
  105.     public boolean isTableExsits() throws SQLException {  
  106.         return getDao().isTableExists();  
  107.     }  
  108.   
  109.     public long countOf() throws SQLException {  
  110.         return getDao().countOf();  
  111.     }  
  112.   
  113.     public List<T> query(Map<String, Object> map) throws SQLException {  
  114.         QueryBuilder<T, Integer> queryBuilder = getDao().queryBuilder();  
  115.         if (!map.isEmpty()) {  
  116.             Where<T, Integer> wheres = queryBuilder.where();  
  117.             Set<String> keys = map.keySet();  
  118.             ArrayList<String> keyss = new ArrayList<String>();  
  119.             keyss.addAll(keys);  
  120.             for (int i = 0; i < keyss.size(); i++) {  
  121.                 if (i == 0) {  
  122.                     wheres.eq(keyss.get(i), map.get(keyss.get(i)));  
  123.                 } else {  
  124.                     wheres.and().eq(keyss.get(i), map.get(keyss.get(i)));  
  125.                 }  
  126.             }  
  127.         }  
  128.         PreparedQuery<T> preparedQuery = queryBuilder.prepare();  
  129.         return query(preparedQuery);  
  130.     }  
  131.   
  132.     public List<T> query(Map<String, Object> map, Map<String, Object> lowMap,  
  133.             Map<String, Object> highMap) throws SQLException {  
  134.         QueryBuilder<T, Integer> queryBuilder = getDao().queryBuilder();  
  135.         Where<T, Integer> wheres = queryBuilder.where();  
  136.         if (!map.isEmpty()) {  
  137.             Set<String> keys = map.keySet();  
  138.             ArrayList<String> keyss = new ArrayList<String>();  
  139.             keyss.addAll(keys);  
  140.             for (int i = 0; i < keyss.size(); i++) {  
  141.                 if (i == 0) {  
  142.                     wheres.eq(keyss.get(i), map.get(keyss.get(i)));  
  143.                 } else {  
  144.                     wheres.and().eq(keyss.get(i), map.get(keyss.get(i)));  
  145.                 }  
  146.             }  
  147.         }  
  148.         if (!lowMap.isEmpty()) {  
  149.             Set<String> keys = lowMap.keySet();  
  150.             ArrayList<String> keyss = new ArrayList<String>();  
  151.             keyss.addAll(keys);  
  152.             for (int i = 0; i < keyss.size(); i++) {  
  153.                 if(map.isEmpty()){  
  154.                     wheres.gt(keyss.get(i), lowMap.get(keyss.get(i)));  
  155.                 }else{  
  156.                     wheres.and().gt(keyss.get(i), lowMap.get(keyss.get(i)));  
  157.                 }  
  158.             }  
  159.         }  
  160.   
  161.         if (!highMap.isEmpty()) {  
  162.             Set<String> keys = highMap.keySet();  
  163.             ArrayList<String> keyss = new ArrayList<String>();  
  164.             keyss.addAll(keys);  
  165.             for (int i = 0; i < keyss.size(); i++) {  
  166.                 wheres.and().lt(keyss.get(i), highMap.get(keyss.get(i)));  
  167.             }  
  168.         }  
  169.         PreparedQuery<T> preparedQuery = queryBuilder.prepare();  
  170.         return query(preparedQuery);  
  171.     }  
  172. }</pre><br>  
  173. 3)怎么应用  
  174. <pre></pre>  
  175. <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 {  
  176.     /** 
  177.      * 
  178.      */  
  179.     private static final long serialVersionUID = 1L;</p><p>    // 流水号ID  
  180.     @DatabaseField(generatedId = true, columnName = "cash_flow_id")  
  181.     private long cashFlowId;</p><p>    // 类型:0收,1支  
  182.     @DatabaseField(canBeNull = false, columnName = "type")  
  183.     private int type;</p><p>    // 资金类型 - 0 贷款,1借款,2货款,3其他  
  184.     @DatabaseField(canBeNull = false, columnName = "cash_type")  
  185.     private int cashType;</p><p>    // 资金类型为其他是的 描述  
  186.     @DatabaseField(columnName = "other_type_desc")  
  187.     private String otherTypeDesc;</p><p>    // 是否参与核销:0否,1是  
  188.     @DatabaseField(canBeNull = false, columnName = "write_off_flag")  
  189.     private int writeOffFlag;</p><p>    // 关联用户ID  
  190.     // private long referUserId;  
  191.     @DatabaseField(foreign = true, foreignAutoRefresh = true, columnName = "phone_book_id")  
  192.     private PhoneBook referUser;</p><p>    // 资金  
  193.     @DatabaseField(canBeNull = false, columnName = "amount")  
  194.     private double amount;</p><p>    // 登记日期  
  195.     @DatabaseField(canBeNull = false, columnName = "reg_date")  
  196.     private long regDate;</p><p>    // 创建时间  
  197.     @DatabaseField(canBeNull = false, columnName = "create_date")  
  198.     private long createDate;</p><p>    // 修改时间  
  199.     @DatabaseField(canBeNull = false, columnName = "update_date")  
  200.     private long updateDate;</p><p>    // 关联账单ID  
  201.     @DatabaseField(foreign = true, foreignAutoRefresh = true, columnName = "bill_id")  
  202.     private Bill referBill;</p><p>    public long getCashFlowId() {  
  203.         return cashFlowId;  
  204.     }</p><p>    public void setCashFlowId(long cashFlowId) {  
  205.         this.cashFlowId = cashFlowId;  
  206.     }</p><p>    public int getType() {  
  207.         return type;  
  208.     }</p><p>    public void setType(int type) {  
  209.         this.type = type;  
  210.     }</p><p>    public int getCashType() {  
  211.         return cashType;  
  212.     }</p><p>    public void setCashType(int cashType) {  
  213.         this.cashType = cashType;  
  214.     }</p><p>    public String getOtherTypeDesc() {  
  215.         return otherTypeDesc;  
  216.     }</p><p>    public void setOtherTypeDesc(String otherTypeDesc) {  
  217.         this.otherTypeDesc = otherTypeDesc;  
  218.     }</p><p>    public int getWriteOffFlag() {  
  219.         return writeOffFlag;  
  220.     }</p><p>    public void setWriteOffFlag(int writeOffFlag) {  
  221.         this.writeOffFlag = writeOffFlag;  
  222.     }</p><p>    public PhoneBook getReferUser() {  
  223.         return referUser;  
  224.     }</p><p>    public void setReferUser(PhoneBook referUser) {  
  225.         this.referUser = referUser;  
  226.     }</p><p>    public double getAmount() {  
  227.         return amount;  
  228.     }</p><p>    public void setAmount(double amount) {  
  229.         this.amount = amount;  
  230.     }</p><p>    public long getRegDate() {  
  231.         return regDate;  
  232.     }</p><p>    public void setRegDate(long regDate) {  
  233.         this.regDate = regDate;  
  234.     }</p><p>    public long getCreateDate() {  
  235.         return createDate;  
  236.     }</p><p>    public void setCreateDate(long createDate) {  
  237.         this.createDate = createDate;  
  238.     }</p><p>    public long getUpdateDate() {  
  239.         return updateDate;  
  240.     }</p><p>    public void setUpdateDate(long updateDate) {  
  241.         this.updateDate = updateDate;  
  242.     }</p><p>    public Bill getReferBill() {  
  243.         return referBill;  
  244.     }</p><p>    public void setReferBill(Bill referBill) {  
  245.         this.referBill = referBill;  
  246.     }</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) {  
  247.   super(context);  
  248.  }</p><p> @Override  
  249.  public Dao<CashFlow, Integer> getDao() throws SQLException {  
  250.   return getHelper().getDao(CashFlow.class);  
  251.  }</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")  
  252.     private void queCashFlow(int msgType, long lowTime, long highTime) {  
  253.         try {  
  254.             CashFlowDao cashFlowDao = new CashFlowDao(this);  
  255.             Map<String, Object> map = new HashMap<String, Object>();  
  256.             Map<String, Object> lowMap = new HashMap<String, Object>();  
  257.             lowMap.put("create_date", lowTime);  
  258.             Map<String, Object> highMap = new HashMap<String, Object>();  
  259.             highMap.put("create_date", highTime);  
  260.             ArrayList<CashFlow> cashFlows = (ArrayList<CashFlow>)cashFlowDao.query(map, lowMap,  
  261.                     highMap);  
  262.             if (cashFlows != null && cashFlows.size() > 0) {  
  263.                 Message message = new Message();  
  264.                 message.what = msgType;  
  265.                 message.obj = cashFlows;  
  266.                 handler.sendMessage(message);  
  267.             } else {  
  268.                 handler.sendEmptyMessage(4);  
  269.             }  
  270.         } catch (SQLException e) {  
  271.             handler.sendEmptyMessage(4);  
  272.         }  
  273.     }</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>  
  274. <p><br>  
  275.  </p>  
  276.       
  277.         <div style="padding-top:20px">           
  278.             <p style="font-size:12px;">版权声明:本文为博主原创文章,未经博主允许不得转载。</p>  
  279.         </div> 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值