比较出名的数据库框架
GreenDao使用步骤:
1、app目录下的build.gradle文件 添加依赖
compile 'org.greenrobot:greendao:3.2.0'
顶部添加插件
apply plugin: 'org.greenrobot.greendao'
2、根目录下的build.gradle文件 配置
dependencies { classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1' }
3、app目录下的build.gradle文件 对generator生成文件配置
greendao { schemaVersion 1//数据库版本号 daoPackage 'com.xxx.xxx.base.database'//设置DaoMaster、DaoSession、Dao包名 targetGenDir 'src/main/java'//设置DaoMaster、DaoSession、Dao目录 //targetGenDirTest:设置生成单元测试目录 //generateTests:设置自动生成单元测试用例 }
dependencies{}
4、创建实体类,生成dao文件
@Entity public class HX_User { @Id private String id; private String userName; private String avatar; }
5、make project
6、检测
HX_User类会变成下面情况,注意 属性值的get和set方法不要自己写,是make project之后自动生成的
@Entity public class HX_User { @Id private String id; private String userName; private String avatar; @Generated(hash = 546596795) public HX_User(String id, String userName, String avatar) { this.id = id; this.userName = userName; this.avatar = avatar; } @Generated(hash = 1952360032) public HX_User() { } public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getUserName() { return this.userName; } public void setUserName(String userName) { this.userName = userName; } public String getAvatar() { return this.avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } }
7、使用:初始化
在自己的Application类中进行初始化
public class XApplication extends Application{ private static DaoSession mDaoSession; @Override public void onCreate() { super.onCreate(); // 初始化数据库 setupDataBase(this); } private void setupDataBase(Context context){ DaoMaster.DevOpenHelper openHelper = new DaoMaster.DevOpenHelper(context,"HX_DB"); Database db = openHelper.getWritableDb(); DaoMaster daoMaster = new DaoMaster(db); mDaoSession = daoMaster.newSession(); } public static DaoSession getDaoSession(){ return mDaoSession; } }
8、使用:增删改查
XApplication.getDaoSession().getHX_UserDao().insertOrReplace(currentUser);
XApplication.getDaoSession().getHX_UserDao().delete(currentUser);
XApplication.getDaoSession().getHX_UserDao().update(currentUser);
List<HX_User> list = XApplication.getDaoSession().getHX_UserDao().queryBuilder().where(HX_UserDao.Properties.Id.eq(uid)).list();