GreenDao3.0的最佳实践

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

官网https://github.com/greenrobot/greenDAO

AndroidStudio的项目配置

 

  1. 基本配置
    1. app内部build.gradle的配置
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1'
    }
}

apply plugin: 'org.greenrobot.greendao'

dependencies {
    compile 'org.greenrobot:greendao:3.2.0'
}

greendao {
    targetGenDir 'src/main/java'
    schemaVersion 9
}

        2.项目build.gradle的配置

buildscript {
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'
    }
}

 

定义一个DB管理工具

/**
 * 数据库管理工具
 */
public class DBManager {
    private DaoMaster.DevOpenHelper devOpenHelper;
    private static DBManager instance;
    private static final String DB_NAME = "xxx.db";

    private DBManager() {
        devOpenHelper = new DaoMaster.DevOpenHelper(MyApplication.getInstance(), DB_NAME, null);
    }

    public static DBManager getInstance() {
        if (instance == null) {
            instance = new DBManager();
        }
        return instance;
    }

    public SQLiteDatabase getWritableDatabase() {
        if (devOpenHelper == null) {
            devOpenHelper = new DaoMaster.DevOpenHelper(MyApplication.getInstance(), DB_NAME, null);
        }
        SQLiteDatabase db = devOpenHelper.getWritableDatabase();
        return db;
    }

}

定义一个Bean

/**
 * 用户管理表
 */
@Entity
@SuppressWarnings("serial")
public class UserInfo implements Serializable {
    @Id(autoincrement = true)
    private Long uId;
    private int uType;
    private String uPwd;
}

定义好后重新编译该工程会自动生成多个文件,

DaoMaster

DaoSession

UserInfoDao

不要动这些文件

 

 

定义一个用户操作类 单例


/**
 * 用户管理类
 */

public class UserInfoModel {
    private DaoMaster daoMaster;
    private DaoSession daoSession;
    private UserInfoDao userInfoDao;
    private static UserInfoModel mUserInfoModel;

    private UserInfoModel() {
        daoMaster = new DaoMaster(DBManager.getInstance().getWritableDatabase());
        daoSession = daoMaster.newSession();
        userInfoDao = daoSession.getUserInfoDao();
    }

    public static UserInfoModel getInstance() {
        if (mUserInfoModel == null) {
            mUserInfoModel = new UserInfoModel();
        }
        return mUserInfoModel;
    }


    /**
     * 用户登陆
     *
     * @param uid
     * @param upwd
     * @return
     */
    public UserInfo login(String uid, String upwd) {
        QueryBuilder qb = userInfoDao.queryBuilder();
        qb.where(UserInfoDao.Properties.UId.eq(uid), UserInfoDao.Properties.UPwd.eq(upwd));
        UserInfo userInfos = qb.build().unique();
        return userInfos;
    }


    /**
     * 根据用户ID删除用户
     */
    public void deleteUserById(String uId) {
        QueryBuilder qb = userInfoDao.queryBuilder();
        DeleteQuery dq = qb.where(UserInfoDao.Properties.UId.eq(uId)).buildDelete();
        dq.executeDeleteWithoutDetachingEntities();
    }

    /**
     * 修改用户密码
     */
    public UserInfo modifyUserPwd(String uId, String oldPwd, String newPwd) {
        //验证旧密码
        UserInfo mUserInfo = login(uId, oldPwd);
        if (mUserInfo == null) {
            return null;
        }
        QueryBuilder qb = userInfoDao.queryBuilder();
        qb.where(UserInfoDao.Properties.UId.eq(uId));
        UserInfo userInfo = qb.build().unique();
        if (userInfo != null) {
            userInfo.setUPwd(newPwd);
            //更新密码
            userInfoDao.update(userInfo);
            mUserInfo = login(uId, newPwd);
            return mUserInfo;
        }
        return null;
    }

    /**
     * 获取用户列表
     *
     * @return
     */
    public List queryAllUser() {
        QueryBuilder qb = userInfoDao.queryBuilder();
        List userInfos = qb.build().list();
        return userInfos;
    }

    /**
     * 根据用户UID查询UserInfo
     *
     * @param uid
     * @return
     */
    public UserInfo queryUserInfoById(String uid) {
        QueryBuilder qb = userInfoDao.queryBuilder();
        qb.where(UserInfoDao.Properties.UId.eq(uid));
        UserInfo userInfo = qb.build().unique();
        return userInfo;
    }

}

 

 

然后就可以根据UserInfoModel .getInstance()拿到单例进行增删改查了

 

GreenDao遇到的坑列表:

 

  1. org.greenrobot:greendao-gradle-plugin:3.2.0这个插件有bug 导致无法自动生成代码,解决方法:要用org.greenrobot:greendao-gradle-plugin:3.2.1这个插件,而这个插件要用classpath 'com.android.tools.build:gradle:2.2.3'以上的gradle下载
  2. 定义自增长id一定要用Long类型
  3. 表字段的bean对象要实现序列化 Serializable 接口类上要加@SuppressWarnings("serial")注解否则无法实现序列化
  4. GeenDao的缓存最为坑  由于QueryBuilder这种对象查询出来的对象被缓存下来了,如果你修改了查询出来的对象的属性,当你再调用该查询方法的时候,该方法不会去重新调用sql 而是把上次查询出来的对象重新赋值给你,该对象也就是你修改过属性的对象====》
    1. 解决办法
      1. 在你查询方法前加上daoSession.clear();
      2. 查询方法后加上xxxDao.detachAll();
        1. public xxx getLastData() {
              daoSession.clear();
          
              QueryBuilder qb = xxxDao.queryBuilder();
              qb.orderDesc(xxxDao.Properties.PDID).limit(1);
              xxx xxx= qb.build().unique();
          
              xxxDao.detachAll();
              return xxx;
          }
    2. 解决办法
      1. 或者你用这种方式获取daoSession就拿到不需要缓存的dao 
        daoSession = daoMaster.newSession(IdentityScopeType.None);

转载于:https://my.oschina.net/547217475/blog/848029

你可能感兴趣的:(java,python,移动开发)