1、构建文件夹存放自动生成的代码,并在脚本中配置:
sourceSets {
main {
java.srcDirs = ['src/main/java', 'src/main/java-gen']
}
}
2、工程配置,引入greenDao
compile 'de.greenrobot:greendao:1.3.7'
3、构建一个java Libarory类型的Module用以生成DAO代码,如下:
该Module需要添加依赖:
compile 'de.greenrobot:greendao-generator:1.3.1'
public class Generator { public static void main(String[] args) throws Exception { Schema schema = new Schema(1, "com.example.greendao"); Entity userInfo = schema.addEntity("UserInfo"); userInfo.addIdProperty().primaryKey().autoincrement(); userInfo.addStringProperty("username").notNull(); userInfo.addStringProperty("password").notNull(); new DaoGenerator().generateAll(schema, "/Users/fredric/Documents/03.document/01.Android/GdDemo02/app/src/main/java-gen"); } }
备注该Module执行后将在java-gen下生成对应的Model和Dao代码。
4、数据库操作:
fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(getApplicationContext(), "myDb", null); SQLiteDatabase db = helper.getWritableDatabase(); DaoMaster daoMaster = new DaoMaster(db); DaoSession daoSession = daoMaster.newSession(); UserInfo info1 = new UserInfo(); info1.setUsername("fredric"); info1.setPassword("2313"); daoSession.getUserInfoDao().insert(info1); List<UserInfo> list = daoSession.getUserInfoDao().loadAll(); for(UserInfo item:list){ System.out.println(item.getUsername()); System.out.println(item.getPassword()); System.out.println(item.getId()); } } }); }