导入步骤:
第一步: 在项目的.gradle文件里面添加
buildscript {
repositories {
google()
jcenter()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.3'
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
第二步:在moddle的.gradle文件里面添加
apply plugin: 'org.greenrobot.greendao'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.****"
*******
}
greendao {
schemaVersion 1 //版本
daoPackage 'com.puppy.***.databases' // 一般为app包名+生成文件的文件夹名
targetGenDir 'src/main/java' //生成文件路径
}
}
dependencies {
implementation 'org.greenrobot:greendao:3.2.2' // add library
implementation 'org.greenrobot:greendao-generator:3.2.2'
}
第三步: 添加Bean类,用User举例子 , 一定要记得注解@Entity 如:
@Entity(nameInDb = "ums_manager_entity")
public class UmsManagerEntity {
@Id(autoincrement = true)
private Long id;
private String module_id;//模块ID/*
private String module_name;//模块说明/*
private String event_id;//事件id/*
private String event_name;//事件名称/*
private int event_type;//事件类型 0基础使用 1中级使用 2高级使用/*
private String lable_id;//lableID
private String lable_name;//lable说明
private String key_id;//keyID
private String key_name;//key说明
private Long value;//值/*
private Long start_time;//开始时间
private Long end_time;//结束时间
第四步:编译项目(执行Make Project),PhoneContactsEntity实体类会自动编译,生成get、set方法并且会在com.puppy.***.databases目录下生成三个文件;
使用步骤:
第一步:使用 DaoMaster.OpenHelper 也可自己继承 DaoMaster.OpenHelper 类;方便自己创建和升级
说明:使用内部DaoMaster.OpenHelper在数据库升级时候数据会丢失;
在这里,使用到这个工具类,升级数据就不会丢失。
public class UmsOpenHelper extends DaoMaster.OpenHelper {
public UmsOpenHelper(Context context, String name) {
super(context, name);
}
public UmsOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
super(context, name, factory);
}
@Override
public void onCreate(Database db) {
createAllTables(db, true);
}
@Override
public void onUpgrade(Database db, int oldVersion, int newVersion) {
//把需要管理的数据库表DAO作为最后一个参数传入到方法中
migrate(db, new MigrationHelper.ReCreateAllTableListener() {
@Override
public void onCreateAllTables(Database db, boolean ifNotExists) {
createAllTables(db, ifNotExists);
}
@Override
public void onDropAllTables(Database db, boolean ifExists) {
DaoMaster.dropAllTables(db, ifExists);
}
}, UmsManagerEntityDao.class); //更新的内容
}
}
这个是网上找的工具类,升级时用到;如果项目用不到升级数据库,可以不需要添加
public final class MigrationHelper {
public static boolean DEBUG = false;
private static String TAG = "MigrationHelper";
private static final String SQLITE_MASTER = "sqlite_master";
private static final String SQLITE_TEMP_MASTER = "sqlite_temp_master";
private static WeakReference<ReCreateAllTableListener> weakListener;
public interface ReCreateAllTableListener{
void onCreateAllTables(Database db, boolean ifNotExists);
void onDropAllTables(Database db, boolean ifExists);
}
public static void migrate(SQLiteDatabase db, Class<? extends AbstractDao<?, ?>>... daoClasses) {
printLog("【The Old Database Version】" + db.getVersion());
Database database = new StandardDatabase(db);
migrate(database, daoClasses);
}
public static void migrate(SQLiteDatabase db, ReCreateAllTableListener listener, Class<? extends AbstractDao<?, ?>>... daoClasses) {
weakListener = new WeakReference<>(listener);
migrate(db, daoClasses);
}
public static void migrate(Database database, ReCreateAllTableListener listener, Class<? extends AbstractDao<?, ?>>... daoClasses) {
weakListener = new WeakReference<>(listener);
migrate(database, daoClasses);
}
public static void migrate(Database database, Class<? extends AbstractDao<?, ?>>... daoClasses) {
printLog("【Generate temp table】start");
generateTempTables(database, daoClasses);
printLog("【Generate temp table】complete");
ReCreateAllTableListener listener = null;
if (weakListener != null) {
listener = weakListener.get();
}
if (listener != null) {
listener.onDropAllTables(database, true);
printLog("【Drop all table by listener】");
listener.onCreateAllTables(database, false);
printLog("【Create all table by listener】");
} else {
dropAllTables(database, true, daoClasses);
createAllTables(database, false, daoClasses);
}
printLog("【Restore data】start");
restoreData(database, daoClasses);
printLog("【Restore data】complete");
}
private static void generateTempTables(Database db, Class<? extends AbstractDao<?, ?>>... daoClasses) {
for (int i = 0; i < daoClasses.length; i++) {
String tempTableName = null;
DaoConfig daoConfig = new DaoConfig(db, daoClasses[i]);
String tableName = daoConfig.tablename;
if (!isTableExists(db, false, tableName)) {
printLog("【New Table】" + tableName);
continue;
}
try {
tempTableName = daoConfig.tablename.concat("_TEMP");
StringBuilder dropTableStringBuilder = new StringBuilder();
dropTableStringBuilder.append("DROP TABLE IF EXISTS ").append(tempTableName).append(";");
db.execSQL(dropTableStringBuilder.toString());
StringBuilder insertTableStringBuilder = new StringBuilder();
insertTableStringBuilder.append("CREATE TEMPORARY TABLE ").append(tempTableName);
insertTableStringBuilder.append(" AS SELECT * FROM ").append(tableName).append(";");
db.execSQL(insertTableStringBuilder.toString());
printLog("【Table】" + tableName +"\n ---Columns-->"+getColumnsStr(daoConfig));
printLog("【Generate temp table】" + tempTableName);
} catch (SQLException e) {
Log.e(TAG, "【Failed to generate temp table】" + tempTableName, e);
}
}
}
private static boolean isTableExists(Database db, boolean isTemp, String tableName) {
if (db == null || TextUtils.isEmpty(tableName)) {
return false;
}
String dbName = isTemp ? SQLITE_TEMP_MASTER : SQLITE_MASTER;
String sql = "SELECT COUNT(*) FROM " + dbName + " WHERE type = ? AND name = ?";
Cursor cursor=null;
int count = 0;
try {
cursor = db.rawQuery(sql, new String[]{"table", tableName});
if (cursor == null || !cursor.moveToFirst()) {
return false;
}
count = cursor.getInt(0);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null)
cursor.close();
}
return count > 0;
}
private static String getColumnsStr(DaoConfig daoConfig) {
if (daoConfig == null) {
return "no columns";
}
StringBuilder builder = new StringBuilder();
for (int i = 0; i < daoConfig.allColumns.length; i++) {
builder.append(daoConfig.allColumns[i]);
builder.append(",");
}
if (builder.length() > 0) {
builder.deleteCharAt(builder.length() - 1);
}
return builder.toString();
}
private static void dropAllTables(Database db, boolean ifExists, @NonNull Class<? extends AbstractDao<?, ?>>... daoClasses) {
reflectMethod(db, "dropTable", ifExists, daoClasses);
printLog("【Drop all table by reflect】");
}
private static void createAllTables(Database db, boolean ifNotExists, @NonNull Class<? extends AbstractDao<?, ?>>... daoClasses) {
reflectMethod(db, "createTable", ifNotExists, daoClasses);
printLog("【Create all table by reflect】");
}
/**
* dao class already define the sql exec method, so just invoke it
*/
private static void reflectMethod(Database db, String methodName, boolean isExists, @NonNull Class<? extends AbstractDao<?, ?>>... daoClasses) {
if (daoClasses.length < 1) {
return;
}
try {
for (Class cls : daoClasses) {
Method method = cls.getDeclaredMethod(methodName, Database.class, boolean.class);
method.invoke(null, db, isExists);
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
private static void restoreData(Database db, Class<? extends AbstractDao<?, ?>>... daoClasses) {
for (int i = 0; i < daoClasses.length; i++) {
DaoConfig daoConfig = new DaoConfig(db, daoClasses[i]);
String tableName = daoConfig.tablename;
String tempTableName = daoConfig.tablename.concat("_TEMP");
if (!isTableExists(db, true, tempTableName)) {
continue;
}
try {
// get all columns from tempTable, take careful to use the columns list
List<TableInfo> newTableInfos = TableInfo.getTableInfo(db, tableName);
List<TableInfo> tempTableInfos = TableInfo.getTableInfo(db, tempTableName);
ArrayList<String> selectColumns = new ArrayList<>(newTableInfos.size());
ArrayList<String> intoColumns = new ArrayList<>(newTableInfos.size());
for (TableInfo tableInfo : tempTableInfos) {
if (newTableInfos.contains(tableInfo)) {
String column = '`' + tableInfo.name + '`';
intoColumns.add(column);
selectColumns.add(column);
}
}
// NOT NULL columns list
for (TableInfo tableInfo : newTableInfos) {
if (tableInfo.notnull && !tempTableInfos.contains(tableInfo)) {
String column = '`' + tableInfo.name + '`';
intoColumns.add(column);
String value;
if (tableInfo.dfltValue != null) {
value = "'" + tableInfo.dfltValue + "' AS ";
} else {
value = "'' AS ";
}
selectColumns.add(value + column);
}
}
if (intoColumns.size() != 0) {
StringBuilder insertTableStringBuilder = new StringBuilder();
insertTableStringBuilder.append("REPLACE INTO ").append(tableName).append(" (");
insertTableStringBuilder.append(TextUtils.join(",", intoColumns));
insertTableStringBuilder.append(") SELECT ");
insertTableStringBuilder.append(TextUtils.join(",", selectColumns));
insertTableStringBuilder.append(" FROM ").append(tempTableName).append(";");
db.execSQL(insertTableStringBuilder.toString());
printLog("【Restore data】 to " + tableName);
}
StringBuilder dropTableStringBuilder = new StringBuilder();
dropTableStringBuilder.append("DROP TABLE ").append(tempTableName);
db.execSQL(dropTableStringBuilder.toString());
printLog("【Drop temp table】" + tempTableName);
} catch (SQLException e) {
Log.e(TAG, "【Failed to restore data from temp table 】" + tempTableName, e);
}
}
}
private static List<String> getColumns(Database db, String tableName) {
List<String> columns = null;
Cursor cursor = null;
try {
cursor = db.rawQuery("SELECT * FROM " + tableName + " limit 0", null);
if (null != cursor && cursor.getColumnCount() > 0) {
columns = Arrays.asList(cursor.getColumnNames());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null)
cursor.close();
if (null == columns)
columns = new ArrayList<>();
}
return columns;
}
private static void printLog(String info){
if(DEBUG){
Log.d(TAG, info);
}
}
private static class TableInfo {
int cid;
String name;
String type;
boolean notnull;
String dfltValue;
boolean pk;
@Override
public boolean equals(Object o) {
return this == o
|| o != null
&& getClass() == o.getClass()
&& name.equals(((TableInfo) o).name);
}
@Override
public String toString() {
return "TableInfo{" +
"cid=" + cid +
", name='" + name + '\'' +
", type='" + type + '\'' +
", notnull=" + notnull +
", dfltValue='" + dfltValue + '\'' +
", pk=" + pk +
'}';
}
private static List<TableInfo> getTableInfo(Database db, String tableName) {
String sql = "PRAGMA table_info(" + tableName + ")";
printLog(sql);
Cursor cursor = db.rawQuery(sql, null);
if (cursor == null)
return new ArrayList<>();
TableInfo tableInfo;
List<TableInfo> tableInfos = new ArrayList<>();
while (cursor.moveToNext()) {
tableInfo = new TableInfo();
tableInfo.cid = cursor.getInt(0);
tableInfo.name = cursor.getString(1);
tableInfo.type = cursor.getString(2);
tableInfo.notnull = cursor.getInt(3) == 1;
tableInfo.dfltValue = cursor.getString(4);
tableInfo.pk = cursor.getInt(5) == 1;
tableInfos.add(tableInfo);
// printLog(tableName + ":" + tableInfo);
}
cursor.close();
return tableInfos;
}
}
}
第二步:封装DatabaseManager工具类
1.声明数据库名字
private static final String DB_NAME = "ums_databases";//数据库名字
private UmsOpenHelper mHelper;
private SQLiteDatabase db;
private DaoMaster mDaoMaster;
private DaoSession mDaoSession;
2.创建DaoSession
public DaoSession getDaoSession(){
if(mDaoSession == null){
if(mDaoMaster == null){
mDaoMaster = getDaoMaster();
}
mDaoSession = mDaoMaster.newSession();
}
return mDaoSession;
}
3. 创建DaoMaster
private DaoMaster getDaoMaster(){
if(mDaoMaster == null){
mHelper = new UmsOpenHelper(mContext, DB_NAME, null);
// 注意:该数据库连接属于 DaoMaster,所以多个 Session 指的是相同的数据库连接。
db = mHelper.getWritableDatabase();
mDaoMaster = new DaoMaster(db);
}
return mDaoMaster;
}
创建完成,具体工具类如下:
public class DatabaseManager {
private static final String DB_NAME = "ums_databases";
private Context mContext;
private UmsOpenHelper mHelper;
private SQLiteDatabase db;
private DaoMaster mDaoMaster;
private DaoSession mDaoSession;
@SuppressLint("StaticFieldLeak")
private volatile static DatabaseManager daoManager = new DatabaseManager();
public static DatabaseManager getInstance(){
return daoManager;
}
public void init(Context context){
this.mContext = context;
}
private DaoMaster getDaoMaster(){
if(mDaoMaster == null){
mHelper = new UmsOpenHelper(mContext, DB_NAME, null);
// 注意:该数据库连接属于 DaoMaster,所以多个 Session 指的是相同的数据库连接。
db = mHelper.getWritableDatabase();
mDaoMaster = new DaoMaster(db);
}
return mDaoMaster;
}
public DaoSession getDaoSession(){
if(mDaoSession == null){
if(mDaoMaster == null){
mDaoMaster = getDaoMaster();
}
mDaoSession = mDaoMaster.newSession();
}
return mDaoSession;
}
public UmsOpenHelper getmHelper(){
if(mHelper == null){
mHelper = new UmsOpenHelper(mContext, DB_NAME, null);
}
return mHelper;
}
public SQLiteDatabase getDb() {
return db;
}
public static String getTableName(){
return "ums_manager_entity";
}
public void setDebug(){
QueryBuilder.LOG_SQL = true;
QueryBuilder.LOG_VALUES = true;
}
public void closeConnection(){
closeHelper();
closeDaoSession();
}
private void closeHelper(){
if(mHelper != null){
mHelper.close();
mHelper = null;
}
}
private void closeDaoSession(){
if(mDaoSession != null){
mDaoSession.clear();
mDaoSession = null;
}
}
}
第三步:调用创建 在Application 中创建
public class UmsApplication extends Application {
public static final String appKey ="952948093568265943";//UMS TEST
public static final String appSecret="9a922945dde3t4dy89jd4ei8494u2r25eb7c4d8r";//umstest secrect key
public static final String sysversion="TAACHOP0100141904271D";//or set empty like "";
public static final String channel = "puppy";
public static final int env=1;//0 debug; 1 release;
//静态单例
public static UmsApplication instances;
private DaoSession mDaoSession;
@Override
public void onCreate()
{
super.onCreate();
instances = this;
setDatabase();
}
public static UmsApplication getInstances(){
return instances;
}
/**
* 设置greenDao
*/
private void setDatabase() {
DatabaseManager databaseManager = DatabaseManager.getInstance();
databaseManager.init(this);
mDaoSession = databaseManager.getDaoSession();
}
public DaoSession getDaoSession() {
return mDaoSession;
}
}
第四步:对表的操作,实现增删该查:
创建UmsManagerUtils工具类
public class UmsManagerUtils {
private static final String TAG = UmsManagerUtils.class.getSimpleName();
private static UmsManagerUtils instance;
private UmsManagerEntityDao umsEntityDao;
private DaoSession daoSession;
private UmsManagerUtils() {
umsEntityDao = UmsApplication.getInstances().getDaoSession().getUmsManagerEntityDao();
daoSession = UmsApplication.getInstances().getDaoSession();
}
//***初始化
public static UmsManagerUtils getInstance() {
if (instance == null) {
synchronized (UmsManagerUtils.class) {
if (instance == null) {
instance = new UmsManagerUtils();
}
}
}
return instance;
}
//***添加
public synchronized boolean insert(UmsManagerEntity entity){
UmsManagerEntity temp = umsEntityDao.queryBuilder()
.where(UmsManagerEntityDao.Properties.Event_id.eq(entity.getEvent_id())).build().unique();
if(temp != null){
Long value = entity.getValue();
Long valueDataBases = temp.getValue();
temp.setValue(value+valueDataBases);
return updateDevice(temp);
}else{
return umsEntityDao.insert(entity) != -1;
}
}
public synchronized boolean insertByLable(UmsManagerEntity entity){
UmsManagerEntity temp = umsEntityDao.queryBuilder()
.where(UmsManagerEntityDao.Properties.Event_id.eq(entity.getEvent_id()),UmsManagerEntityDao.Properties.Lable_id.eq(entity.getLable_id())).build().unique();
if(temp != null){
Long value = entity.getValue();
Long valueDataBases = temp.getValue();
temp.setValue(value+valueDataBases);
return updateDevice(temp);
}else{
return umsEntityDao.insert(entity) != -1;
}
}
public boolean insertMultDevices(final List<UmsManagerEntity> UmsManagerEntityList){
boolean flag = false;
try{
daoSession.runInTx(new Runnable() {
@Override
public void run() {
for(UmsManagerEntity device : UmsManagerEntityList){
updateDevice(device);
}
}
});
flag = true;
}catch(Exception e){
e.printStackTrace();
flag = false;
}
return flag;
}
///****更新
public synchronized boolean updateDevice(UmsManagerEntity device){
boolean flag = false;
try {
umsEntityDao.update(device);
flag = true;
}catch (Exception e){
e.printStackTrace();
}
return flag;
}
///**根据对象删除 单个字段对比
public boolean deleteDeviceEvent(UmsManagerEntity device){
boolean flag = false;
try {
UmsManagerEntity temp = umsEntityDao.queryBuilder()
.where(UmsManagerEntityDao.Properties.Event_id.eq(device.getEvent_id())).build().unique();
umsEntityDao.delete(temp);
flag = true;
}catch (Exception e){
e.printStackTrace();
}
return flag;
}
///**根据对象删除 多个字段对比
public boolean deleteDeviceKey(UmsManagerEntity device){
boolean flag = false;
try {
UmsManagerEntity temp = umsEntityDao.queryBuilder()
.where(UmsManagerEntityDao.Properties.Event_id.eq(device.getEvent_id()),UmsManagerEntityDao.Properties.Lable_id.eq(device.getLable_id()),UmsManagerEntityDao.Properties.Key_id.eq(device.getKey_id())).build().unique();
umsEntityDao.delete(temp);
flag = true;
}catch (Exception e){
e.printStackTrace();
}
return flag;
}
//***删除所有
public synchronized boolean deleteAll(){
boolean flag = false;
try {
daoSession.deleteAll(UmsManagerEntity.class);
flag = true;
}catch (Exception e){
e.printStackTrace();
}
return flag;
}
//**查询搜索
public List<UmsManagerEntity> queryAllDevices(){
return daoSession.loadAll(UmsManagerEntity.class);
}
//根据字段查询
public List<UmsManagerEntity> queryDeviceByTypeId(int event_type)
{
List<UmsManagerEntity> list = umsEntityDao.queryBuilder()
.where(UmsManagerEntityDao.Properties.Event_type.eq(event_type)).build().list();
return list;
}
}
第五步:调用很简单
UmsManagerEntity managerEntityTime = new UmsManagerEntity();
managerEntityTime.setModule_id(Content.MODULE_ID_ROM_PROJECT);
managerEntityTime.setModule_name(Content.MODULE_NAME_ROM_PROJECT);
managerEntityTime.setValue(timeValue);
UmsManagerUtils.getInstance().insert(managerEntityTime);
数据库升级:
1. 直接修改 Entity Bean,修改或添加你想要的属性
2.修改升级 app.build
schemaVersion 1 //版本
3.在OpenHelper
onUpgrade方法中,升级
其他技巧:
1.where 和whereOr的使用
whereOr :或条件查询 多个或用“,”分隔
where:和条件查询 多个和用“,”分隔
例如:当前用户,展示状态 查询用户手机号码或姓名中包含有关键字的人
List list = phoneContactsEntityDao.queryBuilder().whereOr(PhoneContactsEntityDao.Properties.Phone.like("%" + key + "%"),PhoneContactsEntityDao.Properties.Name.like("%" + key + "%")).where(PhoneContactsEntityDao.Properties.IsShow.eq("1"), PhoneContactsEntityDao.Properties.LogingId.eq(ConfigUtils.getUid())).build().list();
2.GreeDao使用sql语句 ,如果满足不了需求,可以使用Sql语句
String sql = "update `" + talbelName + "` set `USER_SATE` = '1' where `LOGING_ID` = '" + ConfigUtils.getUid() + "' and PHONE='" + upSateContacts.get(i).getPhone() + "'";
daoSession.getDatabase().execSQL(sql);