ps:感谢祥哥(鸿洋_)、感谢同事在学习上的帮助,让我这么快就对ORMLite这个框架有了一个初步的了解。下面是我学习中的简单记录。
ORMLite简化了对SQLite的操作,提高了开发效率,减少了维护成本。主要是简化表操作,体现在不用SQL语句。在创建表时,使用bean对象;在数据操作时,使用的是具体方法。
一、简单入门
完整的使用ORMLite需要5步:
- 引入相应包
- 创建bean对象类
- 创建DataHelper类
- 创建Dao类
- 具体使用Dao类
体会:这些步骤都比较常规。bean对象提供实体的基本属性和set|get方法,为后面DateHelper创建表提供模板;DateHelper实现数据库和数据表的创建和维护;Dao提供对表数据的具体操作。其中,前两者的操作比较固定,Dao的活动性很大。
更详细的示例,参考祥哥博客。
二、重点总结
表
表的维护,使用注解@DatabaseTable(tableName = “tb_user”),标明表名tb_user
@DatabaseField(columnName = “name”) ,标明列名name
@DatabaseField(generatedId = true) ,标明id为主键且自动生成
@DatabaseField(canBeNull = true, foreign = true, columnName = “user_id”)其中,canBeNull -表示不能为null;foreign=true表示是一个外键;columnName 列名表操作
Dao.queryForId(id);—返回bean对象
Dao.updateRaw(statement, arguments);–更新
Dao.deleteRaw(statement, arguments);—删除
Dao.queryBuilder().where().eq(“user_id”, userId).query(); —–返回List< bean>
三、重要代码
- bean对象
package com.xueyibao.moudle;
import java.util.Collection;
import com.j256.ormlite.dao.ForeignCollection;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.field.ForeignCollectionField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable(tableName = "ChatMsg")
public class ChatMsg {
@DatabaseField(generatedId = true)
public long id = 0;
@DatabaseField
public Boolean isUser;
@DatabaseField
public String timeStr = "";
@DatabaseField
public String content = "";
@DatabaseField
public String imgUrl = "";
@DatabaseField
public String answerType = "";
@DatabaseField
public String userkey = "";
@ForeignCollectionField
public ForeignCollection<MultipleAnswer> multipleAnswer;
@ForeignCollectionField
public ForeignCollection<MultipleSchoolAnswer> multipleSchoolAnswer;
public Boolean getIsUser() {
return isUser;
}
public void setIsUser(Boolean isUser) {
this.isUser = isUser;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTimeStr() {
return timeStr;
}
public void setTimeStr(String timeStr) {
this.timeStr = timeStr;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public String getAnswerType() {
return answerType;
}
public void setAnswerType(String answerType) {
this.answerType = answerType;
}
public ForeignCollection<MultipleAnswer> getMultipleAnswer() {
return multipleAnswer;
}
public void setMultipleAnswer(ForeignCollection<MultipleAnswer> multipleAnswer) {
this.multipleAnswer = multipleAnswer;
}
public String getUserkey() {
return userkey;
}
public void setUserkey(String userkey) {
this.userkey = userkey;
}
public ForeignCollection<MultipleSchoolAnswer> getMultipleSchoolAnswer() {
return multipleSchoolAnswer;
}
public void setMultipleSchoolAnswer(
ForeignCollection<MultipleSchoolAnswer> multipleSchoolAnswer) {
this.multipleSchoolAnswer = multipleSchoolAnswer;
}
}
2.DataHelper
package com.xueyibao.tookit.db;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.xueyibao.XueyibaoApplication;
/**
* 数据库访问帮助类<br>
* --主要是实现和数据库和数据表有关的操作
* @version 1.0
*/
public class ToolDatabase extends OrmLiteSqliteOpenHelper {
private static String databaseName;
private static int databaseVersion;
@SuppressWarnings("rawtypes")
private static List<Class> table = new ArrayList<Class>();
private static ToolDatabase dbHelper = null;
/**
* 必须对外提供Public构造函数(实例化不用该方法)
* @param context 上下文
*/
public ToolDatabase(Context context) {
super(context, databaseName, null, databaseVersion);
}
/**
* 实例化对象
* @param dbName 数据库名称
* @param version 数据库版本
* @return
*/
public static ToolDatabase gainInstance(String dbName, int version) {
if (dbHelper == null) {
databaseName = dbName;
databaseVersion = version;
//会隐式调用public构造方法
dbHelper = OpenHelperManager.getHelper(XueyibaoApplication.getContext(), ToolDatabase.class);
}
return dbHelper;
}
/**
* 释放数据库连接
*/
public void releaseAll() {
if (dbHelper != null) {
OpenHelperManager.releaseHelper();
dbHelper = null;
}
}
/**
* 配置实体
* @param cls 实体
*/
@SuppressWarnings("rawtypes")
public void addEntity(Class cls) {
table.add(cls);
}
/**
* 删除表
* @param entity 实体
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public void dropTable(Class entity) {
try {
TableUtils.dropTable(getConnectionSource(), entity, true);
} catch (SQLException e) {
Log.e(ToolDatabase.class.getName(), "Unable to drop table", e);
}
}
/**
* 创建表
* @param entity 实体
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public void createTable(Class entity) {
try {
TableUtils.createTableIfNotExists(getConnectionSource(), entity);
} catch (SQLException e) {
Log.e(ToolDatabase.class.getName(), "Unable to create table", e);
}
}
/**
* 创建SQLite数据库
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void onCreate(SQLiteDatabase sqliteDatabase,
ConnectionSource connectionSource) {
try {
for (Class entity : table) {
TableUtils.createTableIfNotExists(connectionSource, entity);
}
} catch (SQLException e) {
Log.e(ToolDatabase.class.getName(), "Unable to create datbases", e);
}
}
/**
* 更新SQLite数据库
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void onUpgrade(SQLiteDatabase sqliteDatabase,
ConnectionSource connectionSource, int oldVer, int newVer) {
try {
for (Class entity : table) {
TableUtils.dropTable(connectionSource, entity, true);
}
onCreate(sqliteDatabase, connectionSource);
} catch (SQLException e) {
Log.e(ToolDatabase.class.getName(),
"Unable to upgrade database from version " + oldVer
+ " to new " + newVer, e);
}
}
}
3.Dao
package com.xueyibao.tookit.db;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import com.j256.ormlite.android.AndroidDatabaseConnection;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.xueyibao.moudle.ChatMsg;
import com.xueyibao.tookit.ConstantDB;
/**
* 保存智能机器人聊天数据库工具类
*/
public class DataBaseUtilChatMsg {
public Context mContext;
public ToolDatabase dbHelper;
public Dao<ChatMsg, String> chatDao;
public DataBaseUtilChatMsg(Context mContext) {
super();
this.mContext = mContext;
}
/**
* 初始化数据库
*/
@SuppressWarnings("unchecked")
public void initDataBaseHelp() {
//实例化dbHelper
dbHelper = ToolDatabase.gainInstance(ConstantDB.ChatMsg, ConstantDB.DBVersion);
dbHelper.createTable(ChatMsg.class);
try {
chatDao = (Dao<ChatMsg, String>)dbHelper.getDao(ChatMsg.class);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
*根据ask 查询详情
* @return
*/
public List<ChatMsg> getChatMsgFromDatabase(String userkey) {
List<ChatMsg> chatMsgs = new ArrayList<ChatMsg>();
try {
QueryBuilder qb = chatDao.queryBuilder();
qb.orderBy("timeStr", true).where().eq("userkey", userkey);
PreparedQuery<ChatMsg> pq = qb.prepare();
return chatDao.query(pq);
} catch (SQLException e) {
e.printStackTrace();
return chatMsgs;
}
}
/**
*根据ID 查询详情
* @return
*/
public ChatMsg getChatMsgById(String id) {
ChatMsg chatMsg = new ChatMsg();
try {
chatMsg = chatDao.queryForId(id);
} catch (SQLException e) {
e.printStackTrace();
}
return chatMsg;
}
/**
*根据ask 查询详情
* @return
*/
public List<ChatMsg> getChatMsgByContent(String content,String userkey) {
List<ChatMsg> chatMsgs = new ArrayList<ChatMsg>();
try {
QueryBuilder qb = chatDao.queryBuilder();
qb.orderByRaw(" timeStr desc ").where().like("content", "%"+content+"%").and().eq("userkey", userkey);
PreparedQuery<ChatMsg> pq = qb.prepare();
return chatDao.query(pq);
} catch (SQLException e) {
e.printStackTrace();
return chatMsgs;
}
}
/**
* 添加聊天记录
* @param schoolKey
*/
public void addChatMsg(ChatMsg chatMsg) {
try {
AndroidDatabaseConnection conn = null;
//获取数据库连接
conn = new AndroidDatabaseConnection(dbHelper.getWritableDatabase(), true);
conn.setAutoCommit(false);
chatDao.create(chatMsg);
//提交事务
conn.commit(null);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 清除所有聊天记录
*/
public void clearAllChatMsgs() {
dbHelper.dropTable(ChatMsg.class);
}
}