为什么80%的码农都做不了架构师?>>>
这里记录ormlite的原因:有很多效率更高的数据库 比如greendao,但是使用中会有很多问题,比如greendao是自动化build的,而且需要改gradle中的配置,这就可能影响当前项目的使用。当时有个项目使用jni,
dependencies { classpath 'com.android.tools.build:gradle:3.1.3' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files }
greendao的配置跟项目使用的jni需要的配置冲突,很是麻烦。
ormlite的优点很明显,引入jar包,其他代码随便撸。
虽然缺点是慢,但是移动端的优化真的不在数据库这点时间,在其他方面有更大的优化空间
注意:bean成员变量用public
必须有空构造方法
dao =super.getDao(clazz);这里clazz千万不能用clazz.getClass()
有的时候dao =super.getDao(clazz);报红,是因为JDK高版本可以不显示强制转化,低版本不行,加上强转语法就行。
ormlite incompatible types required
public synchronized Dao getDao(Class clazz) throws SQLException { Dao dao = null; String className = clazz.getSimpleName(); if (daos.containsKey(className)) { dao = daos.get(className); } if (dao == null) { dao = (Dao)super.getDao(clazz); daos.put(className, dao); } return dao; }
package com.fnf.aiui.databases;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
/**
* Created by wfy 2017/7/5 11:25.
*/
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public interface OnCreateListener {
void onCreate(SQLiteDatabase database, ConnectionSource connectionSource);
void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion);
}
private static OnCreateListener onCreateListener;
public static void setDbInfo(String dbName, int dbVersion, OnCreateListener listener) {
DB_NAME = dbName;
DB_VERSION = dbVersion;
onCreateListener = listener;
}
/**
* 数据库名字
*/
private static String DB_NAME;
/**
* 数据库版本
*/
private static int DB_VERSION;
private Map daos = new HashMap<>();
private DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
if(onCreateListener!=null)onCreateListener.onCreate(database,connectionSource);
}
@Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
if(onCreateListener!=null)onCreateListener.onUpgrade(database,connectionSource,oldVersion,newVersion);
}
private static DatabaseHelper instance;
/** 单例获取该Helper */
public static synchronized DatabaseHelper getHelper(Context context) {
context = context.getApplicationContext();
if (instance == null) {
synchronized (DatabaseHelper.class) {
if (instance == null) {
instance = new DatabaseHelper(context);
}
}
}
return instance;
}
@SuppressWarnings("unchecked")
public synchronized Dao getDao(Class clazz) throws SQLException {
Dao dao = null;
String className = clazz.getSimpleName();
if (daos.containsKey(className)) {
dao = daos.get(className);
}
if (dao == null) {
dao = super.getDao(clazz);
daos.put(className, dao);
}
return dao;
}
/** 释放资源 */
@Override
public void close() {
super.close();
for (String key : daos.keySet()) {
Dao dao = daos.get(key);
dao = null;
}
}
}
package com.fnf.aiui.databases;
import android.content.Context;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.PreparedDelete;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.PreparedUpdate;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.UpdateBuilder;
import com.j256.ormlite.stmt.Where;
import com.j256.ormlite.support.DatabaseConnection;
import java.security.InvalidParameterException;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* 数据库CRUD操作的Dao,子类继承实现抽象方法
* Created by wfy 2017/7/5 11:25.
*/
public abstract class BaseDao {
protected Context mContext;
protected DatabaseHelper mDatabaseHelper;
public BaseDao(Context context) {
if (context == null) {
throw new IllegalArgumentException("Context can't be null!");
}
mContext = context.getApplicationContext();
mDatabaseHelper = DatabaseHelper.getHelper(mContext);
}
/**
* public Dao getDao() throws SQLException
*
* @return
* @throws SQLException
*/
public abstract Dao getDao() throws SQLException;
/**************************************** 保存 ******************************************************/
/**
* 插入一条记录
*
* @param t
*/
public void insert(T t) {
try {
Dao dao = getDao();
dao.create(t);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 插入一组记录,使用事务处理
*
* @param list
*/
public void insertList(List list) {
if (list.size() <= 0) return;
try {
Dao dao = getDao();
DatabaseConnection databaseConnection = null;
try {
databaseConnection = dao.startThreadConnection();
dao.setAutoCommit(databaseConnection, false);
for (T t : list) {
dao.create(t);
// dao.createIfNotExists(t);
}
dao.commit(databaseConnection);
} catch (SQLException e) {
dao.rollBack(databaseConnection);
e.printStackTrace();
} finally {
dao.endThreadConnection(databaseConnection);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**************************************** 更新 ******************************************************/
/**
* 更新一条记录
*
* @param t
*/
public void update(T t) {
try {
Dao dao = getDao();
dao.update(t);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 根据指定条件和指定字段更新记录
*
* @param key
* @param value
* @param columnNames
* @param columnValues
*/
public void update(String key, Object value, String[] columnNames, Object[] columnValues) {
if (columnNames.length != columnNames.length) {
throw new InvalidParameterException("params size is not equal");
}
try {
Dao dao = getDao();
UpdateBuilder updateBuilder = dao.updateBuilder();
updateBuilder.where().eq(key, value);
for (int i = 0; i < columnNames.length; i++) {
updateBuilder.updateColumnValue(columnNames[i], columnValues[i]);
}
PreparedUpdate prepareUpdate = updateBuilder.prepare();
dao.update(prepareUpdate);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 根据指定条件和指定字段更新记录
*
* @param key
* @param value
* @param columnNames
* @param columnValues
*/
public void update(String[] key, Object[] value, String[] columnNames, Object[] columnValues) {
if (columnNames.length != columnNames.length) {
throw new InvalidParameterException("params size is not equal");
}
try {
Dao dao = getDao();
UpdateBuilder updateBuilder = dao.updateBuilder();
Where where = updateBuilder.where();
for (int i = 0; i < key.length; i++) {
if (i == 0) {
where.eq(key[i], value[i]);
} else {
where.and().eq(key[i], value[i]);
}
}
for (int i = 0; i < columnNames.length; i++) {
updateBuilder.updateColumnValue(columnNames[i], columnValues[i]);
}
PreparedUpdate prepareUpdate = updateBuilder.prepare();
dao.update(prepareUpdate);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 根据PreparedUpdate更新记录
*
* @param preparedUpdate
*/
public void update(PreparedUpdate preparedUpdate) {
try {
Dao dao = getDao();
dao.update(preparedUpdate);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**************************************** 保存或更新 ******************************************************/
/**
* 插入或更新一条记录,不存在则插入,否则更新
*
* @param t
*/
public void insertOrUpdate(T t) {
try {
Dao dao = getDao();
dao.createOrUpdate(t);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 插入或更新一组数据,使用事务处理
*
* @param list
*/
public void insertOrUpdate(List list) {
if (list.size() <= 0) return;
try {
Dao dao = getDao();
DatabaseConnection databaseConnection = null;
try {
databaseConnection = dao.startThreadConnection();
dao.setAutoCommit(databaseConnection, false);
for (T t : list) {
dao.createOrUpdate(t);
}
dao.commit(databaseConnection);
} catch (SQLException e) {
dao.rollBack(databaseConnection);
e.printStackTrace();
} finally {
dao.endThreadConnection(databaseConnection);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**************************************** 删除操作 ******************************************************/
/**
* 删除一条记录
*
* @param t
*/
public void delete(T t) {
try {
Dao dao = getDao();
dao.delete(t);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 根据单个条件删除一条记录,如果有多个记录满足该条件,删除查询到的第一条记录
*
* @param columnName
* @param columnValue
*/
public void delete(String columnName, Object columnValue) {
try {
Dao dao = getDao();
QueryBuilder queryBuilder = dao.queryBuilder();
queryBuilder.where().eq(columnName, columnValue);
PreparedQuery preparedQuery = queryBuilder.prepare();
T t = dao.queryForFirst(preparedQuery);
dao.delete(t);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 根据条件组合删除一条记录,如果有多个记录满足该条件,删除查询到的第一条记录
*
* @param columnNames
* @param columnValues
*/
public void delete(String[] columnNames, Object[] columnValues) {
if (columnNames.length != columnNames.length) {
throw new InvalidParameterException("params size is not equal");
}
try {
QueryBuilder queryBuilder = getDao().queryBuilder();
Where wheres = queryBuilder.where();
for (int i = 0; i < columnNames.length; i++) {
if (i == 0) {
wheres.eq(columnNames[i], columnValues[i]);
} else {
wheres.and().eq(columnNames[i], columnValues[i]);
}
}
PreparedQuery preparedQuery = queryBuilder.prepare();
Dao dao = getDao();
T t = dao.queryForFirst(preparedQuery);
delete(t);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 删除一组记录,使用事务处理
* @param list
*/
/**
* 注意:Dao.delete(Collection datas)方法删除,最多只能删除999条记录
**/
public void deleteList(List list) {
if (list.size() <= 0) return;
try {
Dao dao = getDao();
DatabaseConnection databaseConnection = null;
try {
databaseConnection = dao.startThreadConnection();
dao.setAutoCommit(databaseConnection, false);
for (T t : list) {
dao.delete(t);
}
dao.commit(databaseConnection);
} catch (SQLException e) {
dao.rollBack(databaseConnection);
e.printStackTrace();
} finally {
dao.endThreadConnection(databaseConnection);
}
} catch (SQLException e) {
e.printStackTrace();
}
// try {
// Dao dao = getDao();
// dao.delete(list);
// } catch (SQLException e) {
// e.printStackTrace();
// }
}
/**
* 根据条件删除满足条件的所有记录
*
* @param columnName
* @param columnValue
*/
public void deleteList(String columnName, Object columnValue) {
try {
Dao dao = getDao();
DeleteBuilder deleteBuilder = dao.deleteBuilder();
deleteBuilder.where().eq(columnName, columnValue);
PreparedDelete preparedDelete = deleteBuilder.prepare();
dao.delete(preparedDelete);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 根据条件组合删除所有满足条件的记录
*
* @param columnNames
* @param columnValues
*/
public void deleteList(String[] columnNames, Object[] columnValues) {
if (columnNames.length != columnNames.length) {
throw new InvalidParameterException("params size is not equal");
}
try {
Dao dao = getDao();
DeleteBuilder deleteBuilder = dao.deleteBuilder();
Where wheres = deleteBuilder.where();
for (int i = 0; i < columnNames.length; i++) {
if (i == 0) {
wheres.eq(columnNames[i], columnValues[i]);
} else {
wheres.and().eq(columnNames[i], columnValues[i]);
}
}
PreparedDelete preparedDelete = deleteBuilder.prepare();
dao.delete(preparedDelete);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 根据id删除一条记录
*
* @param id
*/
public void deleteById(Integer id) {
try {
Dao dao = getDao();
dao.deleteById(id);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 根据id数组删除一组记录
*
* @param ids
*/
public void deleteByIds(List ids) {
try {
Dao dao = getDao();
dao.deleteIds(ids);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 根据PreparedDelete删除记录
*
* @param preparedDelete
*/
public void delete(PreparedDelete preparedDelete) {
try {
Dao dao = getDao();
dao.delete(preparedDelete);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 删除表中的所有记录
*/
public void deleteAll() {
try {
Dao dao = getDao();
DeleteBuilder deleteBuilder = dao.deleteBuilder();
PreparedDelete preparedDelete = deleteBuilder.prepare();
dao.delete(preparedDelete);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 清空一张表中的数据
*
* @param table 表名
*/
public void clearTable(String table) {
try {
Dao dao = getDao();
String delete = String.format("delete from %s", table);
dao.queryRaw(delete);//清空数据
String updateSeq = String.format("update sqlite_sequence SET seq = 0 where name ='%s'", table);
dao.queryRaw(updateSeq);//自增长ID为0
} catch (SQLException e) {
e.printStackTrace();
}
}
/**************************************** 查询操作 ******************************************************/
/**
* 根据单个条件查询一条记录
*
* @param columnName
* @param columnValue
* @return
*/
public T query(String columnName, Object columnValue) {
try {
Dao dao = getDao();
QueryBuilder queryBuilder = dao.queryBuilder();
queryBuilder.where().eq(columnName, columnValue);
PreparedQuery preparedQuery = queryBuilder.prepare();
T t = dao.queryForFirst(preparedQuery);
return t;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 根据条件组合查询一条记录
*
* @param columnNames
* @param columnValues
* @return
*/
public T query(String[] columnNames, Object[] columnValues) {
if (columnNames.length != columnNames.length) {
throw new InvalidParameterException("params size is not equal");
}
try {
QueryBuilder queryBuilder = getDao().queryBuilder();
Where wheres = queryBuilder.where();
for (int i = 0; i < columnNames.length; i++) {
if (i == 0) {
wheres.eq(columnNames[i], columnValues[i]);
} else {
wheres.and().eq(columnNames[i], columnValues[i]);
}
}
PreparedQuery preparedQuery = queryBuilder.prepare();
Dao dao = getDao();
T t = dao.queryForFirst(preparedQuery);
return t;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 根据PreparedQuery查询所有记录
*
* @param preparedQuery
* @return
*/
public List queryList(PreparedQuery preparedQuery) {
try {
Dao dao = getDao();
DatabaseConnection databaseConnection = null;
try {
databaseConnection = dao.startThreadConnection();
dao.setAutoCommit(databaseConnection, false);
List query = dao.query(preparedQuery);
dao.commit(databaseConnection);
return query;
} catch (SQLException e) {
dao.rollBack(databaseConnection);
e.printStackTrace();
} finally {
dao.endThreadConnection(databaseConnection);
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 根据单个条件查询所有满足条件的记录
*
* @param columnName
* @param columnValue
* @return
*/
public List queryList(String columnName, Object columnValue) {
try {
Dao dao = getDao();
QueryBuilder queryBuilder = dao.queryBuilder();
queryBuilder.where().eq(columnName, columnValue);
PreparedQuery preparedQuery = queryBuilder.prepare();
List query = dao.query(preparedQuery);
return query;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 根据条件组合查询所有满足条件的记录
*
* @param columnNames
* @param columnValues
* @return
*/
public List queryList(String[] columnNames, Object[] columnValues) {
if (columnNames.length != columnNames.length) {
throw new InvalidParameterException("params size is not equal");
}
try {
Dao dao = getDao();
QueryBuilder queryBuilder = dao.queryBuilder();
Where wheres = queryBuilder.where();
for (int i = 0; i < columnNames.length; i++) {
if (i == 0) {
wheres.eq(columnNames[i], columnValues[i]);
} else {
wheres.and().eq(columnNames[i], columnValues[i]);
}
}
PreparedQuery preparedQuery = queryBuilder.prepare();
List query = dao.query(preparedQuery);
return query;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 根据键值对查询所有满足条件的记录
*
* @param map
* @return
*/
public List queryList(Map map) {
try {
Dao dao = getDao();
QueryBuilder queryBuilder = dao.queryBuilder();
if (!map.isEmpty()) {
Where wheres = queryBuilder.where();
Iterator> iterator = map.entrySet().iterator();
String key = null;
Object value = null;
for (int i = 0; iterator.hasNext(); i++) {
Map.Entry next = iterator.next();
key = next.getKey();
value = next.getValue();
if (i == 0) {
wheres.eq(key, value);
} else {
wheres.and().eq(key, value);
}
}
}
PreparedQuery preparedQuery = queryBuilder.prepare();
List query = dao.query(preparedQuery);
return query;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 根据Id查询
*
* @param id
* @return
*/
public T queryById(Integer id) {
try {
Dao dao = getDao();
T t = dao.queryForId(id);
return t;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 查询所有记录
*
* @return
*/
public List queryAll() {
try {
Dao dao = getDao();
List query = dao.queryForAll();
return query;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 条件查询
*
* @param offset 偏移量
* @param limit 查询数量
* @param columnName
* @param columnValue
* @return
*/
public List queryAll(long offset, long limit, String columnName, Object columnValue) {
try {
Dao dao = getDao();
QueryBuilder queryBuilder = dao.queryBuilder();
queryBuilder.offset(offset)
.limit(limit)
.where().eq(columnName, columnValue);
PreparedQuery preparedQuery = queryBuilder.prepare();
List query = dao.query(preparedQuery);
return query;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 条件查询
*
* @param offset 偏移量
* @param limit 查询数量
* @return
*/
public List queryAll(long offset, long limit) {
try {
Dao dao = getDao();
QueryBuilder queryBuilder = dao.queryBuilder();
queryBuilder.offset(offset)
.limit(limit);
PreparedQuery preparedQuery = queryBuilder.prepare();
List query = dao.query(preparedQuery);
return query;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 条件查询
*
* @param offset 偏移量
* @param limit 查询数量
* @param order 排序字段
* @param ascending true--升序 false--降序
* @return
*/
public List queryAll(long offset, long limit, String order, boolean ascending) {
try {
Dao dao = getDao();
QueryBuilder queryBuilder = dao.queryBuilder();
queryBuilder.orderBy(order, ascending)
.offset(offset)
.limit(limit);
PreparedQuery preparedQuery = queryBuilder.prepare();
List query = dao.query(preparedQuery);
return query;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**************************************** 其他操作 ******************************************************/
/**
* 表是否存在
*
* @return true--存在 false-- 不存在
*/
public boolean isTableExists() {
try {
return getDao().isTableExists();
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
/**
* 获得记录数
*
* @return 记录数
*/
public long count() {
try {
Dao dao = getDao();
long count = dao.countOf();
return count;
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
/**
* 获得记录数
*
* @param preparedQuery
* @return 记录数
*/
public long count(PreparedQuery preparedQuery) {
try {
Dao dao = getDao();
long count = dao.countOf(preparedQuery);
return count;
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
}
package com.fnf.aiui.databases;
import android.content.Context;
import com.j256.ormlite.dao.Dao;
import java.sql.SQLException;
/**
* Created by wfy 2017/7/5 10:54.
*
*/
public class BaseDaoImpl extends BaseDao {
private Class clazz;
private Dao dao;
public BaseDaoImpl(Context context, Class clazz) {
super(context);
// TODO Auto-generated constructor stub
this.clazz = clazz;
}
@Override
public Dao getDao() throws SQLException {
// TODO Auto-generated method stub
if (null == dao) {
dao = mDatabaseHelper.getDao(clazz);
}
return dao;
}
}
package com.photo.album.bean;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable(tableName = "table_worker")
public class Worker {
@DatabaseField(generatedId = true)
public int id;
@DatabaseField(columnName = "name")
public String name;
@DatabaseField(columnName = "jobNum")
public long jobNum;
@DatabaseField(columnName = "profession", foreign = true, foreignAutoRefresh = true)
public Profession profession;
public Worker() {
}
public Worker(String name, long jobNum) {
this.name = name;
this.jobNum = jobNum;
}
public Worker(String name, long jobNum, Profession profession) {
this.name = name;
this.jobNum = jobNum;
this.profession = profession;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Worker worker = (Worker) o;
return id == worker.id;
}
@Override
public int hashCode() {
return id;
}
}
package com.photo.album.db;
import android.content.Context;
import com.photo.album.bean.Worker;
import com.wuzhou.wlibrary.db.BaseDaoImpl;
/**
* Created by wfy 2017/7/6 09:20.
*/
public class WorkDao extends BaseDaoImpl {
public WorkDao(Context context) {
super(context, Worker.class);
}
//此处第二个构造方法更好,可以在调用端直接看到绑定的实体类
public WorkDao(Context context, Class clazz) {
super(context, clazz);
}
/**
* 自定义方法,常用的话 为了方便
* @param worker
* @return
*/
public boolean isExist(Worker worker){
boolean b;
if(query("jobNum",worker.jobNum)==null){
b=false;
}else{
b=true;
}
return b;
}
}
DatabaseHelper.setDbInfo("ai_db", 1, new DatabaseHelper.OnCreateListener() {
@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
try {
TableUtils.createTable(connectionSource, HandlerModel.class);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
try {
TableUtils.dropTable(connectionSource, HandlerModel.class, true);
onCreate(database, connectionSource);
} catch (SQLException e) {
e.printStackTrace();
}
}
});