GreenDao依赖在build.gradle(model中)配置
dependencies { compile'org.greenrobot:greendao:3.0.1' compile'org.greenrobot:greendao-generator:3.0.0' }
greenDao中的 三个参数分别是:数据库的版本号、自动生成的工具类名、路径
apply plugin: 'org.greenrobot.greendao' android { buildTypes { } greendao { schemaVersion 1 daoPackage 'com.example.ztz.greendaodemo.dao' targetGenDir 'src/main/java' } }
在build.gradle(project中)配置
dependencies { classpath 'org.greenrobot:greendao-gradle-plugin:3.0.0' }
repositories { mavenCentral() }
创建一个实体类
@Entity表明该类是持久化的类【持久化含义,存入数据库文件中,作本地化处理】
@Id选择一个long或Long类型的属性作为该实体所对应数据库中数据表的主键【类型要是long】
@Generated写在构造方法前
写完之后点击Android Studio上的 Build —>Make Project即可
@Entity public class User { @Id(autoincrement = true) private long id; private String name; private String age; @Generated(hash = 586692638) public User() { } @Generated(hash = 531058479) public User(long id, String name, String age) { this.id = id; this.name = name; this.age = age; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } }
到这里就配置完了,接下来进行初始化,创建MyApplication继承application--------别忘了在清单文件引用MyApplication
public class MyApplication extends Application { public static DaoSession daoSession; @Override public void onCreate() { super.onCreate(); DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "ztz"); Database database = helper.getWritableDb(); daoSession = new DaoMaster(database).newSession(); } }