GreenDao3.2.2简单使用

本文介绍GreenDao作为轻量级ORM框架的优势及应用方法,包括如何配置Gradle插件、定义实体类、创建数据库实例和执行基本的CRUD操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于GreenDao

greenDao是一个将对象映射到SQLite数据库中的轻量且快速的ORM解决方案。
关于greenDAO的概念可以看官网greenDAO

greenDAO 优势

1、一个精简的库
2、性能最大化
3、内存开销最小化
4、易于使用的 APIs
5、对 Android 进行高度优化

GreenDao 3.2.2使用

GreenDao 3.2.2采用注解的方式来定义实体类,通过gradle插件生成相应的代码。

**温馨提示:版本号要一致

一,导入依赖

 

implementation 'org.greenrobot:greendao:3.2.2'

 二,在build.gradle根模块中进行配置: 

   

dependencies {
    classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'
}

三,在build.gradle中进行配置: 

 

apply plugin: 'org.greenrobot.greendao'
android {
    /**
     *  schemaVersion--> 指定数据库schema版本号,迁移等操作会用到;
     *  daoPackage --> dao的包名,包名默认是entity所在的包;
     *  targetGenDir --> 生成数据库文件的目录;
     */
    greendao {
        schemaVersion 1
        daoPackage 'com.gwj.mygreendao.greendao.gen'
        targetGenDir 'src/main/java'
    }
}

 

四,创建一个User的实体类

 

@Entity
public class User {
    @Id
    private Long id;
    private String name;

}

五,Cleap Project

    编译项目,User实体类会自动编译,生成get、set方法并且会在com.gwj.myareendao.greendao.gen目录下生成三个文件;

    

六,创建MyApplicaton(在AndroidManifest.xml文件中注册)

 

public class MyApplication extends Application {
    private DaoMaster.DevOpenHelper mHelper;
    private SQLiteDatabase db;
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;
    public static MyApplication instances;
    @Override
    public void onCreate() {
        super.onCreate();
        instances = this;
        setDatabase();
    }
    public static MyApplication getInstances(){
        return instances;
    }
    private void setDatabase() {
        // 通过 DaoMaster 的内部类 DevOpenHelper,你可以得到一个便利的 SQLiteOpenHelper 对象。
        // 可能你已经注意到了,你并不需要去编写「CREATE TABLE」这样的 SQL 语句,因为 greenDAO 已经帮你做了。
        // 注意:默认的 DaoMaster.DevOpenHelper 会在数据库升级时,删除所有的表,意味着这将导致数据的丢失。
        // 所以,在正式的项目中,你还应该做一层封装,来实现数据库的安全升级。
        mHelper = new DaoMaster.DevOpenHelper(this, "notes-db", null);
        db = mHelper.getWritableDatabase();
        // 注意:该数据库连接属于 DaoMaster,所以多个 Session 指的是相同的数据库连接。
        mDaoMaster = new DaoMaster(db);
        mDaoSession = mDaoMaster.newSession();
    }
    public DaoSession getDaoSession() {
        return mDaoSession;
    }
    public SQLiteDatabase getDb() {
        return db;
    }

}

七,MainActivity

 

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private Button add;
    private Button select;
    private Button replace;
    private Button delete;
    private TextView textView;
    private UserDao userDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();

        userDao = Myapplication.getInstances().getDaoSession().getUserDao();
        
    }

    private void initView() {
        add = (Button) findViewById(R.id.add);
        select = (Button) findViewById(R.id.select);
        replace = (Button) findViewById(R.id.replace);
        delete = (Button) findViewById(R.id.delete);
        textView = (TextView) findViewById(R.id.textView);

        add.setOnClickListener(this);
        select.setOnClickListener(this);
        replace.setOnClickListener(this);
        delete.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            
            case R.id.add:
                User user = new User((long)0,"学习");
                userDao.insert(user);
                Toast.makeText(MainActivity.this,"添加学习成功",Toast.LENGTH_LONG).show();
                break;
               
            case R.id.select:
                List<User> users = userDao.loadAll();
                String userName = "";
                Long userId = null;
                for (int i = 0; i < users.size(); i++) {
                    userName = users.get(i).getName();
                    userId =users.get(i).getId();
                }
                textView.setText(userId+","+userName);
                break;
                
            case R.id.replace:
                User replaceuser=new User((long) 0,"玩耍");
                userDao.update(replaceuser);
                Toast.makeText(MainActivity.this,"玩耍替换学习成功",Toast.LENGTH_LONG).show();
                break;
                
            case R.id.delete:
                //删除全部
                //userDao.deleteAll();
                //根据id进行删除
                userDao.deleteByKey((long)0);
                Toast.makeText(MainActivity.this,"刪除id为0的数据成功",Toast.LENGTH_LONG).show();
                break;
        }
    }

}

 

八,activity_main.xml

 

    

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:text="添加"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:id="@+id/add" />

    <Button
        android:text="查询"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/add"
        android:layout_toEndOf="@+id/add"
        android:layout_marginLeft="10dp"
        android:layout_marginStart="10dp"
        android:id="@+id/select" />

    <Button
        android:text="修改"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/select"
        android:layout_toEndOf="@+id/select"
        android:layout_marginLeft="18dp"
        android:layout_marginStart="18dp"
        android:id="@+id/replace" />

    <Button
        android:text="删除"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:id="@+id/delete" />

    <TextView
        android:text="TextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView"
        android:layout_alignParentBottom="true"
        android:layout_alignLeft="@+id/select"
        android:layout_alignStart="@+id/select"
        android:layout_marginBottom="165dp" />

</RelativeLayout>

greendao中的注解

(一) @Entity 定义实体
@nameInDb 在数据库中的名字,如不写则为实体中类名
@indexes 索引
@createInDb 是否创建表,默认为true,false时不创建
@schema 指定架构名称为实体
@active 无论是更新生成都刷新
(二) @Id
(三) @NotNull 不为null
(四) @Unique 唯一约束
(五) @ToMany 一对多
(六) @OrderBy 排序
(七) @ToOne 一对一
(八) @Transient 不存储在数据库中
(九) @generated 由greendao产生的构造函数或方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值