Well known database framework
Steps to use GreenDao:
1. Add dependency to build.gradle file in app directory
compile 'org.greenrobot:greendao:3.2.0'
Add plug-in at the top
apply plugin: 'org.greenrobot.greendao'
2. Configuration of build.gradle file in root directory
dependencies { classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1' }
3. The build.gradle file in the app directory configures the generated file of the generator
greendao { schemaVersion 1//Database version number daoPackage 'com.xxx.xxx.base.database'//Set up DaoMaster,DaoSession,Dao Package name targetGenDir 'src/main/java'//Set up DaoMaster,DaoSession,Dao Catalog //targetGenDirTest: Set build unit test directory //generateTests: Set up automatic generation of unit test cases }
dependencies{}
4. Create entity class and generate dao file
@Entity public class HX_User { @Id private String id; private String userName; private String avatar; }
5,make project
6. Testing
The HX_User class will change to the following situation. Note that the get and set methods of property values should not be written by yourself. They are generated automatically after 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. Using: initialization
Initialize in your own Application class
public class XApplication extends Application{ private static DaoSession mDaoSession; @Override public void onCreate() { super.onCreate(); // Initialize database 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. Use: add, delete, modify and query
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();