项目导包
classpath'org.greenrobot:greendao-gradle-plugin:3.2.1'
model导包
compile 'org.greenrobot:greendao:3.2.0' compile 'org.greenrobot:greendao-generator:3.2.0'
接着在模块build.gradle的顶部添加
apply plugin: ‘org.greenrobot.greendao’
Bean 类的生成(快捷键ctrl+F9)
@Entity
publicclassUser {
@Id(autoincrement = true)
private Long id;
private String name;
private String sex;
privateint age;
privateint salary;
@Generated(hash = 257789183)
public class MyApplication extends Application { public static DaoSession daoSession; public static boolean ENCRYPTED; @Override public void onCreate() { super.onCreate(); DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, ENCRYPTED ? "users-db-encrypted" : "users-db"); Database db = helper.getWritableDb(); daoSession = new DaoMaster(db).newSession(); } public DaoSession getDaoSession() { return daoSession; } }
//得到GreenDao的查询和修改的对象
private UserBeanDao userDao; private Query<UserBean> userBeanQuery;
DaoSession daoSession = ((App) getApplication()).getDaoSession(); userDao = daoSession.getUserBeanDao(); userBeanQuery = userDao.queryBuilder().orderAsc(UserBeanDao.Properties.Id).build();
@Override public void onClick(View v) { switch (v.getId()) { case R.id.add: userDao.insert(new UserBean( null, "张三", 18)); userDao.insert(new UserBean( null, "李四", 20)); break; case R.id.del: userDao.deleteByKey((long) 1); break; case R.id.update: UserBean userBean = userDao.load((long) 1); userBean.setName("王五"); userDao.update(userBean); break; case R.id.query: List<UserBean> list = userBeanQuery.list(); query_result.setText(list.toString()); break; } }