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

package com.jwzhangjie.capricorntv.bean;

import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

import android.os.Parcel;
import android.os.Parcelable;

/**
 * 
 * @author zj 包含视频的参数 视频的名字 "channel_id":9, "channel_name":"湖南卫视",
 *         "icon_url":"http://tv.togic.com:8080/ShowTimeService/images/182.png",
 *         "province":"湖南", "mode":"SD", "url":
 *         "http://live.gslb.letv.com/gslb?stream_id=hunan&tag=live&ext=m3u8&sign=live_tv&platid=10&splatid=1012&temporarykey=db7c39a0ee39ab2d4d2e781d5"
 *         ,
 *         "second_url":["http://live-cdn.kksmg.com/channels/tvie/test/flv:500k"
 *         ,
 *         "http://live.gslb.letv.com/gslb?stream_id=hunanHD_1800&tag=live&ext=m3u8&sign=live_tv&platid=10&splatid=1012&temporarykey=db7c39a0ee39ab2d4d2e781d5"
 *         ,
 *         "http://pplive.shntv.cn/live/5/30/e9301e073cf94732a380b765c8b9573d.m3u8?type=ipad"
 *         ,"rtsp://rlive.tv189.cn/live/112"], "types":"2|0"
 */

public class LiveItemBean implements Parcelable {

	@Override
	public int describeContents() {
		return 0;
	}

	public LiveItemBean() {
	}

	private LiveItemBean(Parcel source) {
		readFromParcel(source);
	}

	@DatabaseField(id = true)
	private int channel_id;
	@DatabaseField
	private String channel_name;
	@DatabaseField
	private String icon_url;
	@DatabaseField
	private String province;
	@DatabaseField
	private String mode;
	@DatabaseField
	private String url;
	@DatabaseField
	private String second_urls;
	private String[] second_url;
	@DatabaseField
	private String types;

	private void readFromParcel(Parcel source) {
		channel_name = source.readString();
		icon_url = source.readString();
		province = source.readString();
		mode = source.readString();
		url = source.readString();
		second_urls = source.readString();
		second_url = (String[]) source.readArray(LiveItemBean.class
				.getClassLoader());
		types = source.readString();

	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {
		dest.writeInt(channel_id);
		dest.writeString(channel_name);
		dest.writeString(icon_url);
		dest.writeString(province);
		dest.writeString(mode);
		dest.writeString(url);
		dest.writeString(second_urls);
		dest.writeArray(second_url);
		dest.writeString(types);
	}

	public static Creator<LiveItemBean> CREATOR = new Creator<LiveItemBean>() {

		@Override
		public LiveItemBean createFromParcel(Parcel source) {
			return new LiveItemBean(source);
		}

		@Override
		public LiveItemBean[] newArray(int size) {
			return new LiveItemBean[size];
		}
	};

	public int getChannel_id() {
		return channel_id;
	}

	public void setChannel_id(int channel_id) {
		this.channel_id = channel_id;
	}

	public String getChannel_name() {
		return channel_name;
	}

	public void setChannel_name(String channel_name) {
		this.channel_name = channel_name;
	}

	public String getIcon_url() {
		return icon_url;
	}

	public void setIcon_url(String icon_url) {
		this.icon_url = icon_url;
	}

	public String getProvince() {
		return province;
	}

	public void setProvince(String province) {
		this.province = province;
	}

	public String getMode() {
		return mode;
	}

	public void setMode(String mode) {
		this.mode = mode;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getSecond_urls() {
		return second_urls;
	}

	public void setSecond_urls(String second_urls) {
		this.second_urls = second_urls;
	}

	public String[] getSecond_url() {
		return second_url;
	}

	public void setSecond_url(String[] second_url) {
		this.second_url = second_url;
		StringBuffer buffer = new StringBuffer();
		int count = second_url.length;
		for (int i = 0; i < count; i++) {
			buffer.append(second_url[i]);
			if (i != count-1) {
				buffer.append(";");
			}
		}
		second_urls = buffer.toString();
	}

	public String getTypes() {
		return types;
	}

	public void setTypes(String types) {
		this.types = types;
	}
}

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

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

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

二、创建DBHelper

package com.jwzhangjie.capricorntv.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.jwzhangjie.capricorntv.bean.LiveItemBean;

public class DBHelper extends OrmLiteSqliteOpenHelper {
	
	private static final String DATABASE_NAME = "jwzhangjie.db";
	private static final int DATABASE_VERSION = 1;

	public DBHelper(Context context){
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase sqLiteDatabase,
			ConnectionSource connectionSource) {
		try {
			TableUtils.createTable(connectionSource, LiveItemBean.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase sqLiteDatabase,
			ConnectionSource connectionSource, int oldVer, int newVer) {
		try {
			TableUtils.dropTable(connectionSource, LiveItemBean.class, true);
			onCreate(sqLiteDatabase, connectionSource);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
上面使用TableUtils来创建和删除表,还有其他的功能例如清空表内容等

三、创建操作工具

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

package com.jwzhangjie.capricorntv.uitls;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;

import com.j256.ormlite.dao.Dao;
import com.jwzhangjie.capricorntv.bean.LiveItemBean;
import com.jwzhangjie.capricorntv.db.DBHelper;

public class DBUtils {
	
	public static Dao<LiveItemBean, Integer> liveDao = null;

	public DBUtils(Context context) {
		if (liveDao == null) {
			DBHelper dbHelper = new DBHelper(context);
			try {
				liveDao = dbHelper.getDao(LiveItemBean.class);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 插入直播数据,如果数据存在则进行更新
	 * 
	 * @param liveItemBean
	 */
	public void LiveCreate(LiveItemBean liveItemBean) {
		try {
			liveDao.createOrUpdate(liveItemBean);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 连续进行插入,如果存在则更新
	 */
	public void LiveCreates(List<LiveItemBean> lists) {
		try {
			for (LiveItemBean liveItemBean : lists) {
				liveDao.createOrUpdate(liveItemBean);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 查询所有的直播元素
	 * @return
	 */
	public List<LiveItemBean> getLiveItemBeans(){
		List<LiveItemBean> listsBeans = new ArrayList<LiveItemBean>();
		try {
			listsBeans = liveDao.queryForAll();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return listsBeans;
	}

}

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

/**
	 * 连续进行插入,如果存在则更新
	 */
	public void LiveCreates(final List<LiveItemBean> lists) {
		try {
			liveDao.callBatchTasks(new Callable<Void>() {

				@Override
				public Void call() throws Exception {
					for (LiveItemBean liveItemBean : lists) {
						liveDao.createOrUpdate(liveItemBean);
					}
					return null;
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
查询除了用已有的接口,我们还可以使用sql语句来实现,比如:

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

四、最后释放

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

OpenHelperManager.releaseHelper();
		dbHelper = null;



相关推荐
<p> <span style="color:#4d4d4d;">当前课程中博客项目的实战源码是我在 GitHub上开源项目 My-Blog,目前已有 2000 多个 star:</span> </p> <p> <span style="color:#4d4d4d;"><img src="https://img-bss.csdnimg.cn/202103310649344285.png" alt="" /><br /> </span> </p> <p> <span style="color:#4d4d4d;">本课程是一个 Spring Boot 技术栈的实战类课程,课程共分为 3 大部分,前面两个部分为基础环境准备和相关概念介绍,第三个部分是 Spring Boot 个人博客项目功能的讲解,<span style="color:#565656;">通过本课程的学习,不仅仅让你掌握基本的 Spring Boot 开发能力以及 Spring Boot 项目的大部分开发使用场景,同时帮你提前甄别和处理掉将要遇到的技术难点,认真学完这个课程后,你将会对 Spring Boot 有更加深入而全面的了解,同时你也会得到一个大家都在使用的博客系统源码,你可以根据自己的需求和想法进行改造,也可以直接使用它来作为自己的个人网站,这个课程一定会给你带来巨大的收获。</span></span> </p> <p> <span style="color:#4d4d4d;"><span style="color:#565656;"> </span></span> </p> <p> <span style="color:#e53333;"><span style="color:#e53333;"><strong>课程特色</strong></span></span> </p> <p> <span style="color:#e53333;"><span style="color:#e53333;"><strong> </strong></span></span> </p> <p> <span style="color:#4d4d4d;"><span style="color:#565656;"> </span></span> </p> <ol> <li> <span style="color:#565656;">课程内容紧贴 Spring Boot 技术栈,涵盖大部分 Spring Boot 使用场景。</span> </li> <li> <span style="color:#565656;">开发教程详细完整、文档资源齐全、实验过程循序渐进简单明了。</span> </li> <li> <span style="color:#565656;">实践项目页面美观且实用,交互效果完美。</span> </li> <li> <span style="color:#565656;">包含从零搭建项目、以及完整的后台管理系统和博客展示系统两个系统的功能开发流程。</span> </li> <li> <span style="color:#565656;">技术栈新颖且知识点丰富,学习后可以提升大家对于知识的理解和掌握,对于提升你的市场竞争力有一定的帮助。</span> </li> </ol> <p> <strong>实战项目预览</strong> </p> <p> <span style="color:#4d4d4d;"><span style="color:#565656;"><span style="color:#e53333;"><strong> </strong></span></span></span> </p> <p> <span style="color:#4d4d4d;"><img src="https://img-bss.csdn.net/202005150303066258.png" alt="" /><br /> </span> </p> <p>   </p> <p> <span style="color:#4d4d4d;"> </span> </p> <p> <span style="color:#4d4d4d;"><img src="https://img-bss.csdn.net/202005150305396930.png" alt="" /><br /> </span> </p> <p> <span style="color:#4d4d4d;"> </span> </p> <p> <span style="color:#4d4d4d;"><img src="https://img-bss.csdn.net/202005150305528842.png" alt="" /><br /> </span> </p> <p> <span style="color:#4d4d4d;"> </span> </p> <p> <span style="color:#4d4d4d;"><img src="https://img-bss.csdn.net/202005150306056323.png" alt="" /><br /> </span> </p>
©️2020 CSDN 皮肤主题: 程序猿惹谁了 设计师:白松林 返回首页