标签(空格分隔): Android
Ormlite 是什么
其英文全称是:Object Relational Mapping (对象关系映射),简单来说这个框架是协助开放者进行对象关系的构建,并作持久化保存的操作。
Ormlite 的特点
基于反射实现(所以效率会较低),但是使用非常方便
导入
Android Studio 下 ctrl + alt + shift + s,进入到 Project Structure 界面 - Dependencies 下搜索 ormlite 并添加(com.j256.ormlite:ormlite-android:5.0),即可进行使用。
使用步骤
- 新建 DBHelper 继承 OrmLiteSqliteOpenHelper 并重写相应方法
- 新建相应的 beanDao 类进行对改变的增删该查操作
举例
- 以作者与他所创作的笔记为例子
- 一个作者可以对应多种笔记,而每一种笔记只会有一个作者
代码样例
- Author Bean
package com.edu.linnote.bean;
import com.j256.ormlite.dao.ForeignCollection;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.field.ForeignCollectionField;
import com.j256.ormlite.table.DatabaseTable;
import java.io.Serializable;
/**
* Created by liminglin on 17-3-2.
*/
@DatabaseTable(tableName = "author")
public class Author implements Serializable{
@DatabaseField(generatedId = true)
public int id;
@DatabaseField
private String name;
@DatabaseField
private String pwd;
// 一个作者可以对应多个笔记(确立关系的关键)
@ForeignCollectionField(eager = true)
public ForeignCollection<Note> notes;
public String getName() {
return name;
}
public String getPwd() {
return pwd;
}
public void setName(String name) {
this.name = name;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setNotes(ForeignCollection<Note> notes) {
this.notes = notes;
}
public ForeignCollection<Note> getNotes() {
return notes;
}
}
- Note bean
package com.edu.linnote.bean;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import java.io.Serializable;
/**
* Created by liminglin on 17-3-2.
*/
@DatabaseTable(tableName = "note")
public class Note implements Serializable{
@DatabaseField(generatedId = true)
private int id;
/*@DatabaseField(id = true)
private Integer noteId;*/
@DatabaseField
private String title;
@DatabaseField
private String content;
@DatabaseField
private String lastTime;
@DatabaseField
private int category; // 笔记的类别
// 外部对象字段(确立关系的关键)
@DatabaseField(foreign = true,foreignAutoRefresh = true)
public Author author;
public String getTitle() {
return title;
}
public String getContent() {
return content;
}
public String getLastTime() {
return lastTime;
}
public void setTitle(String title) {
this.title = title;
}
public void setContent(String content) {
this.content = content;
}
public void setLastTime(String lastTime) {
this.lastTime = lastTime;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public int getCategory() {
return category;
}
public void setCategory(int category) {
this.category = category;
}
public void setAuthor(Author author) {
this.author = author;
}
public Author getAuthor() {
return author;
}
}
- DBHelper类
package com.edu.linnote.util;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.edu.linnote.bean.Author;
import com.edu.linnote.bean.Note;
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 java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
/**
* Created by liminglin on 17-3-2.
*/
public class DBHelper extends OrmLiteSqliteOpenHelper {
private static final String DB_NAME = "clientmsg.db";
private static final int DB_VERSOIN = 1;
// 用来存放 Dao 的键值对集合
private Map<String,Dao> daos = new HashMap<String,Dao>();
private static DBHelper instance;
private static SPUtil spUtil;
public static DBHelper getInstance(Context context,SPUtil spNewUtil){
if(instance == null){
synchronized (DBHelper.class){
if(instance == null){
instance = new DBHelper(context);
spUtil = spNewUtil;
}
}
}
return instance;
}
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSOIN);
}
/**
* 创建表的操作
* @param database
* @param connectionSource
*/
@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
try {
TableUtils.createTableIfNotExists(connectionSource, Author.class);
TableUtils.createTableIfNotExists(connectionSource, Note.class);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 这里进行更新表操作
* @param database
* @param connectionSource
* @param oldVersion
* @param newVersion
*/
@Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
try {
TableUtils.dropTable(connectionSource,Author.class,true);
TableUtils.dropTable(connectionSource,Note.class,true);
spUtil.setAuthorOnline(false);
onCreate(database,connectionSource);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 通过类来获得指定的 dao
* @param clazz
* @return
* @throws SQLException
*/
/*public synchronized Dao getDao(Class clazz) throws SQLException {
Dao dao = null;
String className = clazz.getSimpleName();
if(daos.containsKey(className)){
dao = super.getDao(clazz);
daos.put(className,dao);
}
return dao;
}*/
/**
* 释放资源
*/
public void close(){
super.close();
for(String key : daos.keySet()){
Dao dao = daos.get(key);
dao = null;
}
}
}
- AuthorDao(NoteDao类似,也可写在一块)
package com.edu.linnote.util;
import android.content.Context;
import com.edu.linnote.bean.Author;
import com.j256.ormlite.dao.Dao;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by liminglin on 17-3-6.
*/
public class AuthorDao{
private Dao<Author,Integer> authorDao;
private DBHelper dbHelper;
private SPUtil spUtil;
public AuthorDao(Context context){
spUtil = new SPUtil(context);
dbHelper = DBHelper.getInstance(context,spUtil);
try {
authorDao = dbHelper.getDao(Author.class);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 添加一条记录
* @param author
*/
public void add(Author author){
try {
authorDao.createOrUpdate(author);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 删除一条记录
* @param author
*/
public void delete(Author author){
try {
authorDao.delete(author);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 更新一条记录
* @param author
*/
public void update(Author author){
try {
authorDao.update(author);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 查询一条记录
* @param name
* @return
*/
public Author queryForName(String name){
try {
List<Author> authors = authorDao.queryForEq("name",name);
if(authors != null && authors.size()>0){
Author author = authors.get(0);
return author;
}else{
return null;
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("查找出现异常.");
}
}
/**
* 查询所有记录
* @return
*/
public List<Author> queryForAll(){
List<Author> authors = new ArrayList<>();
try {
authors = authorDao.queryForAll();
} catch (SQLException e) {
e.printStackTrace();
}
return authors;
}
public boolean isAuthorExit(String name){
List<Author> authors = null;
try {
authors = authorDao.queryForEq("name",name);
if(authors != null && authors.size() == 1){
return true;
}else{
return false;
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("查找用户异常.");
}
}
}
说明
- @DatabaseTable:表示定义一个数据表,若不指定名字则以类名作为表名,指定表明就是在后面加上 (tableName="table_name")
- @DatabaseField:表示定义了一个数据字段,(generatedId = true)表示主键自增
- @ForeignCollectionField(eager=true),用此注解标识的属性属于外键,被标注的外键也需要声明他,从而建立相互的关系
注意点
- 如果项目中存在两张表的互相关系,那么就需要使用外键注解,详细情查看我代码中的使用(就是两个 bean 都要声明具有关系的字段)
- 使用的时候要记得(在构建对象到时候),要记得给外键也附上值
- ForeignCollection<T> 是一个继承 Collection<T> 的接口(List、Set)等继承自这个接口,都是用于处理数据集的接口,使用的方法类似,不过要注意数据的类型
Edited by 李铭淋
2017.3.14
网友评论