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

Android使用Ormlite实现Java Bean的持久化:Dao的封装与使用

2017年12月10日 ⁄ 综合 ⁄ 共 8035字 ⁄ 字号 评论关闭

1.简介
之前做了一段时间的Java Web开发,对于数据库访问,我们使用Hibernate,用起来相当不错。如今做android开发,在使用Sqlite的时候,不禁也会猜测有没有类似Hibernate的ORM框架。结果Google一搜,比较有名的就是ormlite。下面就简单说一下Android中ormlite的使用。
2.ormlite的下载地址:

http://www.ormlite.com/
3.封装与使用

下面我以一个Java Bean为例,简单的对ormlite进行封装。以下是一个聊天消息的JavaBean 取名为ChatMsgEntity
我们不需要在类的前面添加注解,此时,该类映射的数据库表的名称就是类的名称。我们在需要入库的每一个java bean的Field上添加注解,表示这对应着数据库中的字段。对于自增加的主键,我们使用generatedId = true 

package edu.njupt.zhb.model;

import com.j256.ormlite.field.DatabaseField;

/**
 * 一个聊天消息的JavaBean
 *@author: ZhengHaibo  
 *web:     http://blog.csdn.net/nuptboyzhb
 *mail:    zhb931706659@126.com
 *2013-12-23  Nanjing,njupt,China
 */
public class ChatMsgEntity {
	@DatabaseField(generatedId = true)
	private int id;
	@DatabaseField
	private String nickName;//群组的昵称
	@DatabaseField
	private String name;// 消息来自
	@DatabaseField
	private String date;// 消息日期
	@DatabaseField
	private String message;// 消息内容
	@DatabaseField
	private int msgType;// 消息类型
	@DatabaseField
	private boolean recv = true;// 是否为收到的消息

	public int getMsgType() {
		return msgType;
	}

	public ChatMsgEntity() {
		
	}
	public ChatMsgEntity(String name, String date, String message, int msgType,
			boolean recv) {
		super();
		this.name = name;
		this.date = date;
		this.message = message;
		this.msgType = msgType;
		this.recv = recv;
	}

	public boolean isRecv() {
		return recv;
	}

	public void setRecv(boolean recv) {
		this.recv = recv;
	}

	public void setMsgType(int msgType) {
		this.msgType = msgType;
	}

	public String getName() {
		return name;
	}
	public int getId() {
		return id;
	}
	
	public void setId(int id) {
		this.id = id;
	}
	
	public String getNickName() {
		return nickName;
	}
	
	public void setNickName(String nickName) {
		this.nickName = nickName;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDate() {
		return date;
	}

	public void setDate(String date) {
		this.date = date;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


}

实现自己的OrmLiteSqliteOpenHelper

package edu.njupt.zhb.dao;

import java.sql.SQLException;
import java.util.concurrent.atomic.AtomicInteger;

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

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import edu.njupt.zhb.model.ChatMsgEntity;

/**
 * Database helper class used to manage the creation and upgrading of your database. This class also usually provides
 * the DAOs used by the other classes.
 */
public class MsgDatabaseHelper extends OrmLiteSqliteOpenHelper {

	// name of the database file for your application -- change to something appropriate for your app
	private static final String DATABASE_NAME = "chatmsg.db";
	// any time you make changes to your database objects, you may have to increase the database version
	private static final int DATABASE_VERSION = 3;

	// the DAO object we use to access the ChatMsgEntity table
	private Dao<ChatMsgEntity, Integer> simpleDao = null;
	private static final AtomicInteger usageCounter = new AtomicInteger(0);

	// we do this so there is only one helper
	private static MsgDatabaseHelper helper = null;

	private MsgDatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	/**
	 * Get the helper, possibly constructing it if necessary. For each call to this method, there should be 1 and only 1
	 * call to {@link #close()}.
	 */
	public static synchronized MsgDatabaseHelper getHelper(Context context) {
		if (helper == null) {
			helper = new MsgDatabaseHelper(context);
		}
		usageCounter.incrementAndGet();
		return helper;
	}

	/**
	 * 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) {
		try {
			Log.i(MsgDatabaseHelper.class.getName(), "onCreate");
			TableUtils.createTable(connectionSource, ChatMsgEntity.class);
		} catch (SQLException e) {
			Log.e(MsgDatabaseHelper.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) {
		try {
			Log.i(MsgDatabaseHelper.class.getName(), "onUpgrade");
			TableUtils.dropTable(connectionSource, ChatMsgEntity.class, true);
			// after we drop the old databases, we create the new ones
			onCreate(db, connectionSource);
		} catch (SQLException e) {
			Log.e(MsgDatabaseHelper.class.getName(), "Can't drop databases", e);
			throw new RuntimeException(e);
		}
	}

	/**
	 * Returns the Database Access Object (DAO) for our ChatMsgEntity class. It will create it or just give the cached
	 * value.
	 */
	public Dao<ChatMsgEntity, Integer> getChatMsgEntityDao() throws SQLException {
		if (simpleDao == null) {
			simpleDao = getDao(ChatMsgEntity.class);
		}
		return simpleDao;
	}

	/**
	 * Close the database connections and clear any cached DAOs. For each call to {@link #getHelper(Context)}, there
	 * should be 1 and only 1 call to this method. If there were 3 calls to {@link #getHelper(Context)} then on the 3rd
	 * call to this method, the helper and the underlying database connections will be closed.
	 */
	@Override
	public void close() {
		if (usageCounter.decrementAndGet() == 0) {
			super.close();
			simpleDao = null;
			helper = null;
		}
	}
}

定义Dao接口

/*
 * $filename: OrmSqliteDao.java,v $
 * $Date: 2013-12-25  $
 * Copyright (C) ZhengHaibo, Inc. All rights reserved.
 * This software is Made by Zhenghaibo.
 */
package edu.njupt.zhb.dao;

import java.util.List;

import android.R.bool;

/*
 *@author: ZhengHaibo  
 *web:     http://blog.csdn.net/nuptboyzhb
 *mail:    zhb931706659@126.com
 *2013-12-25  Nanjing,njupt,China
 */
public interface OrmSqliteDao<T>{
	public boolean save(T object);
	public boolean saveOrUpdate(T object);
	public List<T> find();
	public boolean update(T object);
	public boolean delete(T object);
	public boolean deleteAll();
	public boolean executeSql(String sql);
	public T  findById();
}

实现OrmLiteDao的封装

/*
 * $filename: ChatMsgEntityDao.java,v $
 * $Date: 2013-12-25  $
 * Copyright (C) ZhengHaibo, Inc. All rights reserved.
 * This software is Made by Zhenghaibo.
 */
package edu.njupt.zhb.dao;

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

import android.content.Context;

import com.j256.ormlite.dao.Dao;

import edu.njupt.zhb.model.ChatMsgEntity;

/*
 *@author: ZhengHaibo  
 *web:     http://blog.csdn.net/nuptboyzhb
 *mail:    zhb931706659@126.com
 *2013-12-25  Nanjing,njupt,China
 */
public class ChatMsgEntityDao implements OrmSqliteDao<ChatMsgEntity> {

	private Dao<ChatMsgEntity, Integer> simpleDao = null;
	public ChatMsgEntityDao(Context context) {
		// TODO Auto-generated constructor stub
		try {
			simpleDao = MsgDatabaseHelper.getHelper(context).getChatMsgEntityDao();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	public boolean save(ChatMsgEntity object) {
		// TODO Auto-generated method stub
		try {
			simpleDao.create(object);
			return true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public List<ChatMsgEntity> find() {
		// TODO Auto-generated method stub
		try {
			List<ChatMsgEntity> result = simpleDao.queryForAll();
			return result;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public boolean update(ChatMsgEntity object) {
		// TODO Auto-generated method stub
		try {
			simpleDao.update(object);
			return true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean delete(ChatMsgEntity object) {
		// TODO Auto-generated method stub
		try {
			simpleDao.delete(object);
			return true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public ChatMsgEntity findById() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean deleteAll() {
		// TODO Auto-generated method stub
		try {
			List<ChatMsgEntity> list = simpleDao.queryForAll();
			for(ChatMsgEntity msg:list){
				delete(msg);
			}
			return true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return false;
	}

	@Override
	public boolean saveOrUpdate(ChatMsgEntity object) {
		// TODO Auto-generated method stub
		try {
			simpleDao.createOrUpdate(object);
			return true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean executeSql(String sql) {
		// TODO Auto-generated method stub
		try {
			simpleDao.executeRaw(sql);
			return true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

}

在Activity中使用Dao对象

OrmSqliteDao<ChatMsgEntity> msgDao = new ChatMsgEntityDao(this);

然后就可以使用msgDao对ChatMsgEntity实体类进行“增删改查”的操作了。

使用心得:

使用起来和Hibernate一样方便。同时,也可以执行原生态的sql语句。

最后,希望大家能够为我投票!2013博客之星投票

http://vote.blog.csdn.net/blogstaritem/blogstar2013/NUPTboyZHB


抱歉!评论已关闭.