`
emowuyi
  • 浏览: 1478988 次
文章分类
社区版块
存档分类
最新评论

Android OrmLite

 
阅读更多

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,代码如下:

  1. <spanstyle="font-size:14px;">packagecom.jwzhangjie.capricorntv.bean;
  2. importcom.j256.ormlite.field.DatabaseField;
  3. importcom.j256.ormlite.table.DatabaseTable;
  4. importandroid.os.Parcel;
  5. importandroid.os.Parcelable;
  6. /**
  7. *
  8. *@authorzj包含视频的参数视频的名字"channel_id":9,"channel_name":"湖南卫视",
  9. *"icon_url":"http://tv.togic.com:8080/ShowTimeService/images/182.png",
  10. *"province":"湖南","mode":"SD","url":
  11. *"http://live.gslb.letv.com/gslb?stream_id=hunan&tag=live&ext=m3u8&sign=live_tv&platid=10&splatid=1012&temporarykey=db7c39a0ee39ab2d4d2e781d5"
  12. *,
  13. *"second_url":["http://live-cdn.kksmg.com/channels/tvie/test/flv:500k"
  14. *,
  15. *"http://live.gslb.letv.com/gslb?stream_id=hunanHD_1800&tag=live&ext=m3u8&sign=live_tv&platid=10&splatid=1012&temporarykey=db7c39a0ee39ab2d4d2e781d5"
  16. *,
  17. *"http://pplive.shntv.cn/live/5/30/e9301e073cf94732a380b765c8b9573d.m3u8?type=ipad"
  18. *,"rtsp://rlive.tv189.cn/live/112"],"types":"2|0"
  19. */
  20. publicclassLiveItemBeanimplementsParcelable{
  21. @Override
  22. publicintdescribeContents(){
  23. return0;
  24. }
  25. publicLiveItemBean(){
  26. }
  27. privateLiveItemBean(Parcelsource){
  28. readFromParcel(source);
  29. }
  30. @DatabaseField(id=true)
  31. privateintchannel_id;
  32. @DatabaseField
  33. privateStringchannel_name;
  34. @DatabaseField
  35. privateStringicon_url;
  36. @DatabaseField
  37. privateStringprovince;
  38. @DatabaseField
  39. privateStringmode;
  40. @DatabaseField
  41. privateStringurl;
  42. @DatabaseField
  43. privateStringsecond_urls;
  44. privateString[]second_url;
  45. @DatabaseField
  46. privateStringtypes;
  47. privatevoidreadFromParcel(Parcelsource){
  48. channel_name=source.readString();
  49. icon_url=source.readString();
  50. province=source.readString();
  51. mode=source.readString();
  52. url=source.readString();
  53. second_urls=source.readString();
  54. second_url=(String[])source.readArray(LiveItemBean.class
  55. .getClassLoader());
  56. types=source.readString();
  57. }
  58. @Override
  59. publicvoidwriteToParcel(Parceldest,intflags){
  60. dest.writeInt(channel_id);
  61. dest.writeString(channel_name);
  62. dest.writeString(icon_url);
  63. dest.writeString(province);
  64. dest.writeString(mode);
  65. dest.writeString(url);
  66. dest.writeString(second_urls);
  67. dest.writeArray(second_url);
  68. dest.writeString(types);
  69. }
  70. publicstaticCreator<LiveItemBean>CREATOR=newCreator<LiveItemBean>(){
  71. @Override
  72. publicLiveItemBeancreateFromParcel(Parcelsource){
  73. returnnewLiveItemBean(source);
  74. }
  75. @Override
  76. publicLiveItemBean[]newArray(intsize){
  77. returnnewLiveItemBean[size];
  78. }
  79. };
  80. publicintgetChannel_id(){
  81. returnchannel_id;
  82. }
  83. publicvoidsetChannel_id(intchannel_id){
  84. this.channel_id=channel_id;
  85. }
  86. publicStringgetChannel_name(){
  87. returnchannel_name;
  88. }
  89. publicvoidsetChannel_name(Stringchannel_name){
  90. this.channel_name=channel_name;
  91. }
  92. publicStringgetIcon_url(){
  93. returnicon_url;
  94. }
  95. publicvoidsetIcon_url(Stringicon_url){
  96. this.icon_url=icon_url;
  97. }
  98. publicStringgetProvince(){
  99. returnprovince;
  100. }
  101. publicvoidsetProvince(Stringprovince){
  102. this.province=province;
  103. }
  104. publicStringgetMode(){
  105. returnmode;
  106. }
  107. publicvoidsetMode(Stringmode){
  108. this.mode=mode;
  109. }
  110. publicStringgetUrl(){
  111. returnurl;
  112. }
  113. publicvoidsetUrl(Stringurl){
  114. this.url=url;
  115. }
  116. publicStringgetSecond_urls(){
  117. returnsecond_urls;
  118. }
  119. publicvoidsetSecond_urls(Stringsecond_urls){
  120. this.second_urls=second_urls;
  121. }
  122. publicString[]getSecond_url(){
  123. returnsecond_url;
  124. }
  125. publicvoidsetSecond_url(String[]second_url){
  126. this.second_url=second_url;
  127. StringBufferbuffer=newStringBuffer();
  128. intcount=second_url.length;
  129. for(inti=0;i<count;i++){
  130. buffer.append(second_url[i]);
  131. if(i!=count-1){
  132. buffer.append(";");
  133. }
  134. }
  135. second_urls=buffer.toString();
  136. }
  137. publicStringgetTypes(){
  138. returntypes;
  139. }
  140. publicvoidsetTypes(Stringtypes){
  141. this.types=types;
  142. }
  143. }
  144. </span>

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

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

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

二、创建DBHelper

  1. <spanstyle="font-size:14px;">packagecom.jwzhangjie.capricorntv.db;
  2. importandroid.content.Context;
  3. importandroid.database.sqlite.SQLiteDatabase;
  4. importcom.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
  5. importcom.j256.ormlite.support.ConnectionSource;
  6. importcom.j256.ormlite.table.TableUtils;
  7. importcom.jwzhangjie.capricorntv.bean.LiveItemBean;
  8. publicclassDBHelperextendsOrmLiteSqliteOpenHelper{
  9. privatestaticfinalStringDATABASE_NAME="jwzhangjie.db";
  10. privatestaticfinalintDATABASE_VERSION=1;
  11. publicDBHelper(Contextcontext){
  12. super(context,DATABASE_NAME,null,DATABASE_VERSION);
  13. }
  14. @Override
  15. publicvoidonCreate(SQLiteDatabasesqLiteDatabase,
  16. ConnectionSourceconnectionSource){
  17. try{
  18. TableUtils.createTable(connectionSource,LiveItemBean.class);
  19. }catch(Exceptione){
  20. e.printStackTrace();
  21. }
  22. }
  23. @Override
  24. publicvoidonUpgrade(SQLiteDatabasesqLiteDatabase,
  25. ConnectionSourceconnectionSource,intoldVer,intnewVer){
  26. try{
  27. TableUtils.dropTable(connectionSource,LiveItemBean.class,true);
  28. onCreate(sqLiteDatabase,connectionSource);
  29. }catch(Exceptione){
  30. e.printStackTrace();
  31. }
  32. }
  33. }
  34. </span>
上面使用TableUtils来创建和删除表,还有其他的功能例如清空表内容等

三、创建操作工具

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

  1. <spanstyle="font-size:14px;">packagecom.jwzhangjie.capricorntv.uitls;
  2. importjava.sql.SQLException;
  3. importjava.util.ArrayList;
  4. importjava.util.List;
  5. importandroid.content.Context;
  6. importcom.j256.ormlite.dao.Dao;
  7. importcom.jwzhangjie.capricorntv.bean.LiveItemBean;
  8. importcom.jwzhangjie.capricorntv.db.DBHelper;
  9. publicclassDBUtils{
  10. publicstaticDao<LiveItemBean,Integer>liveDao=null;
  11. publicDBUtils(Contextcontext){
  12. if(liveDao==null){
  13. DBHelperdbHelper=newDBHelper(context);
  14. try{
  15. liveDao=dbHelper.getDao(LiveItemBean.class);
  16. }catch(SQLExceptione){
  17. e.printStackTrace();
  18. }
  19. }
  20. }
  21. /**
  22. *插入直播数据,如果数据存在则进行更新
  23. *
  24. *@paramliveItemBean
  25. */
  26. publicvoidLiveCreate(LiveItemBeanliveItemBean){
  27. try{
  28. liveDao.createOrUpdate(liveItemBean);
  29. }catch(SQLExceptione){
  30. e.printStackTrace();
  31. }
  32. }
  33. /**
  34. *连续进行插入,如果存在则更新
  35. */
  36. publicvoidLiveCreates(List<LiveItemBean>lists){
  37. try{
  38. for(LiveItemBeanliveItemBean:lists){
  39. liveDao.createOrUpdate(liveItemBean);
  40. }
  41. }catch(Exceptione){
  42. e.printStackTrace();
  43. }
  44. }
  45. /**
  46. *查询所有的直播元素
  47. *@return
  48. */
  49. publicList<LiveItemBean>getLiveItemBeans(){
  50. List<LiveItemBean>listsBeans=newArrayList<LiveItemBean>();
  51. try{
  52. listsBeans=liveDao.queryForAll();
  53. }catch(SQLExceptione){
  54. e.printStackTrace();
  55. }
  56. returnlistsBeans;
  57. }
  58. }
  59. </span>

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

  1. <spanstyle="font-size:14px;">/**
  2. *连续进行插入,如果存在则更新
  3. */
  4. publicvoidLiveCreates(finalList<LiveItemBean>lists){
  5. try{
  6. liveDao.callBatchTasks(newCallable<Void>(){
  7. @Override
  8. publicVoidcall()throwsException{
  9. for(LiveItemBeanliveItemBean:lists){
  10. liveDao.createOrUpdate(liveItemBean);
  11. }
  12. returnnull;
  13. }
  14. });
  15. }catch(Exceptione){
  16. e.printStackTrace();
  17. }
  18. }
  19. </span>
查询除了用已有的接口,我们还可以使用sql语句来实现,比如:

  1. //findouthowmanyordersaccount-id#10has
  2. GenericRawResults<String[]>rawResults=
  3. orderDao.queryRaw(
  4. "selectcount(*)fromorderswhereaccount_id=10");
  5. //thereshouldbe1result
  6. List<String[]>results=rawResults.getResults();
  7. //theresultsarrayshouldhave1value
  8. String[]resultArray=results.get(0);
  9. //thisshouldprintthenumberofordersthathavethisaccount-id
  10. System.out.println("Account-id10has"+resultArray[0]+"orders");

四、最后释放

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

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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics