现在的位置: 首页 > 综合 > 正文

Android OrmLite

2018年03月19日 ⁄ 综合 ⁄ 共 9896字 ⁄ 字号 评论关闭

OrmLite可以帮助我们将会数据库操作,不用自己去写SQL语句,而且设置它跟使用Sqlite一样的方式,它是一种关系型数据,我比较喜欢的就是它能够帮助我判断数据表项是更新还是创建等操作,不需要自己去写大量的SQL语句去判断,下面介绍一下它的使用文档以及一些基本的注意点:

官方网址:http://ormlite.com/

JavaDOC地址:http://ormlite.com/javadoc/ormlite-android/ 

开发文档地址:http://ormlite.com/javadoc/ormlite-core/doc-files/ormlite.html

一、建立模型

首先创建一个Model,作为一个数据表,在Android中我使用的是实现Parcelable,代码如下:

[java] view
plain
copy在CODE上查看代码片派生到我的代码片

  1. <span style="font-size:14px;">package com.jwzhangjie.capricorntv.bean;  
  2.   
  3. import com.j256.ormlite.field.DatabaseField;  
  4. import com.j256.ormlite.table.DatabaseTable;  
  5.   
  6. import android.os.Parcel;  
  7. import android.os.Parcelable;  
  8.   
  9. /** 
  10.  *  
  11.  * @author zj 包含视频的参数 视频的名字 "channel_id":9, "channel_name":"湖南卫视", 
  12.  *         "icon_url":"http://tv.togic.com:8080/ShowTimeService/images/182.png", 
  13.  *         "province":"湖南", "mode":"SD", "url": 
  14.  *         "http://live.gslb.letv.com/gslb?stream_id=hunan&tag=live&ext=m3u8&sign=live_tv&platid=10&splatid=1012&temporarykey=db7c39a0ee39ab2d4d2e781d5" 
  15.  *         , 
  16.  *         "second_url":["http://live-cdn.kksmg.com/channels/tvie/test/flv:500k" 
  17.  *         , 
  18.  *         "http://live.gslb.letv.com/gslb?stream_id=hunanHD_1800&tag=live&ext=m3u8&sign=live_tv&platid=10&splatid=1012&temporarykey=db7c39a0ee39ab2d4d2e781d5" 
  19.  *         , 
  20.  *         "http://pplive.shntv.cn/live/5/30/e9301e073cf94732a380b765c8b9573d.m3u8?type=ipad" 
  21.  *         ,"rtsp://rlive.tv189.cn/live/112"], "types":"2|0" 
  22.  */  
  23.   
  24. public class LiveItemBean implements Parcelable {  
  25.   
  26.     @Override  
  27.     public int describeContents() {  
  28.         return 0;  
  29.     }  
  30.   
  31.     public LiveItemBean() {  
  32.     }  
  33.   
  34.     private LiveItemBean(Parcel source) {  
  35.         readFromParcel(source);  
  36.     }  
  37.   
  38.     @DatabaseField(id = true)  
  39.     private int channel_id;  
  40.     @DatabaseField  
  41.     private String channel_name;  
  42.     @DatabaseField  
  43.     private String icon_url;  
  44.     @DatabaseField  
  45.     private String province;  
  46.     @DatabaseField  
  47.     private String mode;  
  48.     @DatabaseField  
  49.     private String url;  
  50.     @DatabaseField  
  51.     private String second_urls;  
  52.     private String[] second_url;  
  53.     @DatabaseField  
  54.     private String types;  
  55.   
  56.     private void readFromParcel(Parcel source) {  
  57.         channel_name = source.readString();  
  58.         icon_url = source.readString();  
  59.         province = source.readString();  
  60.         mode = source.readString();  
  61.         url = source.readString();  
  62.         second_urls = source.readString();  
  63.         second_url = (String[]) source.readArray(LiveItemBean.class  
  64.                 .getClassLoader());  
  65.         types = source.readString();  
  66.   
  67.     }  
  68.   
  69.     @Override  
  70.     public void writeToParcel(Parcel dest, int flags) {  
  71.         dest.writeInt(channel_id);  
  72.         dest.writeString(channel_name);  
  73.         dest.writeString(icon_url);  
  74.         dest.writeString(province);  
  75.         dest.writeString(mode);  
  76.         dest.writeString(url);  
  77.         dest.writeString(second_urls);  
  78.         dest.writeArray(second_url);  
  79.         dest.writeString(types);  
  80.     }  
  81.   
  82.     public static Creator<LiveItemBean> CREATOR = new Creator<LiveItemBean>() {  
  83.   
  84.         @Override  
  85.         public LiveItemBean createFromParcel(Parcel source) {  
  86.             return new LiveItemBean(source);  
  87.         }  
  88.   
  89.         @Override  
  90.         public LiveItemBean[] newArray(int size) {  
  91.             return new LiveItemBean[size];  
  92.         }  
  93.     };  
  94.   
  95.     public int getChannel_id() {  
  96.         return channel_id;  
  97.     }  
  98.   
  99.     public void setChannel_id(int channel_id) {  
  100.         this.channel_id = channel_id;  
  101.     }  
  102.   
  103.     public String getChannel_name() {  
  104.         return channel_name;  
  105.     }  
  106.   
  107.     public void setChannel_name(String channel_name) {  
  108.         this.channel_name = channel_name;  
  109.     }  
  110.   
  111.     public String getIcon_url() {  
  112.         return icon_url;  
  113.     }  
  114.   
  115.     public void setIcon_url(String icon_url) {  
  116.         this.icon_url = icon_url;  
  117.     }  
  118.   
  119.     public String getProvince() {  
  120.         return province;  
  121.     }  
  122.   
  123.     public void setProvince(String province) {  
  124.         this.province = province;  
  125.     }  
  126.   
  127.     public String getMode() {  
  128.         return mode;  
  129.     }  
  130.   
  131.     public void setMode(String mode) {  
  132.         this.mode = mode;  
  133.     }  
  134.   
  135.     public String getUrl() {  
  136.         return url;  
  137.     }  
  138.   
  139.     public void setUrl(String url) {  
  140.         this.url = url;  
  141.     }  
  142.   
  143.     public String getSecond_urls() {  
  144.         return second_urls;  
  145.     }  
  146.   
  147.     public void setSecond_urls(String second_urls) {  
  148.         this.second_urls = second_urls;  
  149.     }  
  150.   
  151.     public String[] getSecond_url() {  
  152.         return second_url;  
  153.     }  
  154.   
  155.     public void setSecond_url(String[] second_url) {  
  156.         this.second_url = second_url;  
  157.         StringBuffer buffer = new StringBuffer();  
  158.         int count = second_url.length;  
  159.         for (int i = 0; i < count; i++) {  
  160.             buffer.append(second_url[i]);  
  161.             if (i != count-1) {  
  162.                 buffer.append(";");  
  163.             }  
  164.         }  
  165.         second_urls = buffer.toString();  
  166.     }  
  167.   
  168.     public String getTypes() {  
  169.         return types;  
  170.     }  
  171.   
  172.     public void setTypes(String types) {  
  173.         this.types = types;  
  174.     }  
  175. }  
  176. </span>  


我们分析上面的代码同时介绍一下与之相关的配置:

1、是类名,这里我使用的数据表的名字是默认类的小写,当然你还可以指定表名字,使用@DatabaseTable(tableName = "liveitembeans"),

2、主键,在上面的代码中有一行@DatabaseField(id = true)被注解对象就是主键,当然我们有时候使用的一个自增长的id,我们可以设置为@DatabaseField(generatedId = true)来实现,当然还有很多其他的注解配置我这里就不一一说明了,自己可以到官网可以查看找到自己需要的。

二、创建DBHelper

[java] view
plain
copy在CODE上查看代码片派生到我的代码片

  1. <span style="font-size:14px;">package com.jwzhangjie.capricorntv.db;  
  2.   
  3. import android.content.Context;  
  4. import android.database.sqlite.SQLiteDatabase;  
  5.   
  6. import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;  
  7. import com.j256.ormlite.support.ConnectionSource;  
  8. import com.j256.ormlite.table.TableUtils;  
  9. import com.jwzhangjie.capricorntv.bean.LiveItemBean;  
  10.   
  11. public class DBHelper extends OrmLiteSqliteOpenHelper {  
  12.       
  13.     private static final String DATABASE_NAME = "jwzhangjie.db";  
  14.     private static final int DATABASE_VERSION = 1;  
  15.   
  16.     public DBHelper(Context context){  
  17.         super(context, DATABASE_NAME, null, DATABASE_VERSION);  
  18.     }  
  19.   
  20.     @Override  
  21.     public void onCreate(SQLiteDatabase sqLiteDatabase,  
  22.             ConnectionSource connectionSource) {  
  23.         try {  
  24.             TableUtils.createTable(connectionSource, LiveItemBean.class);  
  25.         } catch (Exception e) {  
  26.             e.printStackTrace();  
  27.         }  
  28.     }  
  29.   
  30.     @Override  
  31.     public void onUpgrade(SQLiteDatabase sqLiteDatabase,  
  32.             ConnectionSource connectionSource, int oldVer, int newVer) {  
  33.         try {  
  34.             TableUtils.dropTable(connectionSource, LiveItemBean.classtrue);  
  35.             onCreate(sqLiteDatabase, connectionSource);  
  36.         } catch (Exception e) {  
  37.             e.printStackTrace();  
  38.         }  
  39.     }  
  40.       
  41. }  
  42. </span>  

上面使用TableUtils来创建和删除表,还有其他的功能例如清空表内容等

三、创建操作工具

接下来就是创建一个操作数据库的工具DAO

[java] view
plain
copy在CODE上查看代码片派生到我的代码片

  1. <span style="font-size:14px;">package com.jwzhangjie.capricorntv.uitls;  
  2.   
  3. import java.sql.SQLException;  
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6.   
  7. import android.content.Context;  
  8.   
  9. import com.j256.ormlite.dao.Dao;  
  10. import com.jwzhangjie.capricorntv.bean.LiveItemBean;  
  11. import com.jwzhangjie.capricorntv.db.DBHelper;  
  12.   
  13. public class DBUtils {  
  14.       
  15.     public static Dao<LiveItemBean, Integer> liveDao = null;  
  16.   
  17.     public DBUtils(Context context) {  
  18.         if (liveDao == null) {  
  19.             DBHelper dbHelper = new DBHelper(context);  
  20.             try {  
  21.                 liveDao = dbHelper.getDao(LiveItemBean.class);  
  22.             } catch (SQLException e) {  
  23.                 e.printStackTrace();  
  24.             }  
  25.         }  
  26.     }  
  27.   
  28.     /** 
  29.      * 插入直播数据,如果数据存在则进行更新 
  30.      *  
  31.      * @param liveItemBean 
  32.      */  
  33.     public void LiveCreate(LiveItemBean liveItemBean) {  
  34.         try {  
  35.             liveDao.createOrUpdate(liveItemBean);  
  36.         } catch (SQLException e) {  
  37.             e.printStackTrace();  
  38.         }  
  39.     }  
  40.   
  41.     /** 
  42.      * 连续进行插入,如果存在则更新 
  43.      */  
  44.     public void LiveCreates(List<LiveItemBean> lists) {  
  45.         try {  
  46.             for (LiveItemBean liveItemBean : lists) {  
  47.                 liveDao.createOrUpdate(liveItemBean);  
  48.             }  
  49.         } catch (Exception e) {  
  50.             e.printStackTrace();  
  51.         }  
  52.     }  
  53.       
  54.     /** 
  55.      * 查询所有的直播元素 
  56.      * @return 
  57.      */  
  58.     public List<LiveItemBean> getLiveItemBeans(){  
  59.         List<LiveItemBean> listsBeans = new ArrayList<LiveItemBean>();  
  60.         try {  
  61.             listsBeans = liveDao.queryForAll();  
  62.         } catch (SQLException e) {  
  63.             e.printStackTrace();  
  64.         }  
  65.         return listsBeans;  
  66.     }  
  67.   
  68. }  
  69. </span>  


上面实现了创建和查询,在上面的有一个连续插入多个数据,还可以使用OrmLite提供的批处理任务方法如下:

[java] view
plain
copy在CODE上查看代码片派生到我的代码片

  1. <span style="font-size:14px;">/** 
  2.      * 连续进行插入,如果存在则更新 
  3.      */  
  4.     public void LiveCreates(final List<LiveItemBean> lists) {  
  5.         try {  
  6.             liveDao.callBatchTasks(new Callable<Void>() {  
  7.   
  8.                 @Override  
  9.                 public Void call() throws Exception {  
  10.                     for (LiveItemBean liveItemBean : lists) {  
  11.                         liveDao.createOrUpdate(liveItemBean);  
  12.                     }  
  13.                     return null;  
  14.                 }  
  15.             });  
  16.         } catch (Exception e) {  
  17.             e.printStackTrace();  
  18.         }  
  19.     }  
  20. </span>  

查询除了用已有的接口,我们还可以使用sql语句来实现,比如:

[java] view
plain
copy在CODE上查看代码片派生到我的代码片

  1. // find out how many orders account-id #10 has  
  2.      GenericRawResults<String[]> rawResults =  
  3.        orderDao.queryRaw(  
  4.          "select count(*) from orders where account_id = 10");  
  5.      // there should be 1 result  
  6.      List<String[]> results = rawResults.getResults();  
  7.      // the results array should have 1 value  
  8.      String[] resultArray = results.get(0);  
  9.      // this should print the number of orders that have this account-id  
  10.      System.out.println("Account-id 10 has " + resultArray[0] + " orders"); 

四、最后释放

当我们应用退出时候,我们需要释放之前对象

[java] view
plain
copy在CODE上查看代码片派生到我的代码片

  1. OpenHelperManager.releaseHelper();  
  2.    dbHelper = null;  

抱歉!评论已关闭.