GreenDao是一个基于SQLite的Android ORM嵌入式关系数据库,通过将 Java 对象映射到数据库表(称为 ORM,“对象/关系映射”) ,使用一个简单的面向对象的 API 来存储、更新、删除和查询 Java 对象。
开源Github地址 https://github.com/greenrobot/greenDAO
.gradle
配置- buildscript {
- repositories {
- google()
- jcenter()
- // GreenDao仓库
- mavenCentral()
- }
- dependencies {
- classpath 'com.android.tools.build:gradle:3.5.4'
- // GreenDao插件
- classpath 'org.greenrobot:greendao-gradle-plugin:3.3.0'
- }
- }
.gradle
配置- apply plugin: 'com.android.application'
- //GreenDao插件
- apply plugin: 'org.greenrobot.greendao'
- dependencies {
- // GreenDao依赖添加
- implementation 'org.greenrobot:greendao:3.3.0'
- }
.gradle
配置greenDao基本信息- greendao {
- // 数据库版本号
- schemaVersion 1
- // 生成数据库文件的目录
- targetGenDir 'src/main/java'
- // 生成的数据库相关文件的包名
- daoPackage 'com.clc.greendao_demo.greendao.gen'
- }
- @Entity
- public class User {
- @Id(autoincrement = true)
- private Long id;
-
- @Unique
- private String userId;
-
- @Property
- private String userName;
-
- @Property
- private int age;
- }
创建好实体类,接着Make project(点击小锤子图标),便发现GreenDao为我们的User实体类生成了对应的Getter、Setter方法以及俩个构造函数,同时在我们配置的com.nianlun.greendao.gen
包下生成了三个对应类文件DaoMaster
、DaoSession
和UserDao
,之后所有相关的数据库操作都依靠这三个文件
自动生成GreenDao关键类后,我们要暴露一些公共方法,例如数据库初始化、数据表的增删改查。
- public class DaoManager {
- private static final String TAG = DaoManager.class.getSimpleName();
- private static final String DB_NAME = "CLC_DB";
- private DaoMaster mDaoMaster;
- private DaoMaster.DevOpenHelper mHelper;
- private DaoSession mDaoSession;
- private UserDao mUserDao;
-
- private static class SingletonHolder {
- private static DaoManager instance;
- }
-
- public static DaoManager getInstance() {
- return SingletonHolder.instance;
- }
-
- public static void init(Application application) {
- SingletonHolder.instance = new DaoManager(application);
- }
-
- private DaoManager(Application application) {
- setDebug();
- mHelper = new DaoMaster.DevOpenHelper(application, DB_NAME, null);
- mDaoMaster = new DaoMaster(mHelper.getWritableDatabase());
- mDaoSession = mDaoMaster.newSession();
- mUserDao = mDaoSession.getUserDao();
- }
-
- /**
- * 打开输出日志,默认关闭
- */
- public void setDebug() {
- if (BuildConfig.DEBUG) {
- QueryBuilder.LOG_SQL = true;
- QueryBuilder.LOG_VALUES = true;
- }
- }
-
- /**
- * 关闭所有的操作,数据库开启后,使用完毕要关闭
- */
- public void closeConnection() {
- closeHelper();
- closeDaoSession();
- }
-
- public void closeHelper() {
- if (mHelper != null) {
- mHelper.close();
- mHelper = null;
- }
- }
-
- public void closeDaoSession() {
- if (mDaoSession != null) {
- mDaoSession.clear();
- mDaoSession = null;
- }
- }
-
- /**
- * 增
- */
- public long insert(User user) {
- return mUserDao.insert(user);
- }
-
- /**
- * 查
- */
- public List<User> searchAll() {
- return mUserDao.queryBuilder().list();
- }
- }
- public class MainActivity extends AppCompatActivity {
- private static final String TAG = "MainActivity___";
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- DaoManager.init(getApplication());
- }
-
- @Override
- protected void onResume() {
- super.onResume();
- User user1 = new User(null, "111", "qqq", 33);
- DaoManager.getInstance().insert(user1);
- User user2 = new User(null, "222", "qqq", 33);
- DaoManager.getInstance().insert(user2);
- User user3 = new User(null, "333", "qqq", 33);
- DaoManager.getInstance().insert(user3);
-
- List<User> users = DaoManager.getInstance().searchAll();
- Log.d(TAG, "onResume: " + users);
- }
- }
运行
schema:告知GreenDao当前实体属于哪个schema
active:标记一个实体处于活动状态,活动实体有更新、删除和刷新方法
nameInDb:在数据中使用的别名,默认使用的是实体的类名
indexes:定义索引,可以跨越多个列
createInDb:标记创建数据库表
@Id :主键 Long型,可以通过@Id(autoincrement = true)设置自增长
@Property:设置一个非默认关系映射所对应的列名,默认是的使用字段名 举例:@Property (nameInDb="name")
@NotNul:设置数据库表当前列不能为空
@Transient :添加次标记之后不会生成数据库表的列
@Index:使用@Index作为一个属性来创建一个索引,通过name设置索引别名,也可以通过unique给索引添加约束
@Unique:向数据库列添加了一个唯一的约束
@ToOne:定义与另一个实体(一个实体对象)的关系
@ToMany:定义与多个实体对象的关系
自定义条件删除
mUserDao.queryBuilder().where(UserDao.Properties.Age.eq(33)).buildDelete().executeDeleteWithoutDetachingEntities()
查询所有 mUserDao.queryBuilder().list() 按条件查询 mUserDao.queryBuilder().where(UserDao.Properties.Age.eq(33)).list()
demo:com.android.tools.build:gradle:4.0.1 + gradle-6.4.1-all.zip
一开始使用greenDao版本是3.2.2,项目编译不通过;后来提高greenDao版本到3.3.0就正常了。
报错信息
- Unable to find method 'org.gradle.api.tasks.TaskInputs.property(Ljava/lang/String;Ljava/lang/Object;)Lorg/gradle/api/tasks/TaskInputs;'.
- Possible causes for this unexpected error include:
- Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)
- Re-download dependencies and sync project (requires network)
-
- The state of a Gradle build process (daemon) may be corrupt. Stopping all Gradle daemons may solve this problem.
- Stop Gradle build processes (requires restart)
-
- Your project may be using a third-party plugin which is not compatible with the other plugins in the project or the version of Gradle requested by the project.
-
- In the case of corrupt Gradle processes, you can also try closing the IDE and then killing all Java processes.