Android数据库 GreenDao的使用

本文详细介绍了如何在Android项目中使用GreenDao数据库框架,包括在build.gradle中添加配置,设置数据库版本和DAO包名,创建实体类并定义注解,初始化数据库以及实现增删查改操作。通过自定义MyOpenHelper类和在Application中管理数据库,确保了数据库的高效使用。

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

  • 第一步 先在 项目的Project 的 buil.gradle 里 在buildscript- repositories添加配置mavenCentral();在dependencies 里添加classpath’org.greenrobot:greendao-gradle-plugin:3.0.0’
  • 第二步 在自己想要用的Module 里的 dependencies 里添加
//db
 compile 'org.greenrobot:greendao:3.0.1'
 compile 'org.greenrobot:greendao-generator:3.0.0'
  • android 里 添加
greendao{
schemaVersion 1   
daoPackage 'com.greendao.gen'
targetGenDir 'src/main/java'
}

schemaVersion: 数据库schema版本,也可以理解为数据库版本号
daoPackage:设置DaoMaster、DaoSession、Dao包名
targetGenDir:设置DaoMaster、DaoSession、Dao目录
targetGenDirTest:设置生成单元测试目录
generateTests:设置自动生成单元测试用例

  • 头部 添加
applyplugin:'org.greenrobot.greendao'

第三步 创建新的实体类

@Entity
public class User {   
 @Id(autoincrement = true)    
private Long id;    
private String name;    
private String age;    
private String sex;    
private String salary;
}
  • 实体@Entity注解
    schema:告知GreenDao当前实体属于哪个schema
    active:标记一个实体处于活动状态,活动实体有更新、删除和刷新方法
    nameInDb:在数据中使用的别名,默认使用的是实体的类名
    indexes:定义索引,可以跨越多个列
    createInDb:标记创建数据库表**
  • 基础属性注解
    @Id :主键 Long型,可以通过@Id(autoincrement = true)设置自增长
    @Property:设置一个非默认关系映射所对应的列名,默认是的使用字段名举例:@Property (nameInDb=”name”)
    @NotNul:设置数据库表当前列不能为空
    @Transient:添加次标记之后不会生成数据库表的列

  • 第四步 数据库的初始化

DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(getApplicationContext(), "sql.db", null);  
DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDb());  
DaoSession daoSession = daoMaster.newSession();  
  • 自定义MyOpenHelper 类封装OpenHelper
public class MyOpenHelper extends DaoMaster.OpenHelper {

    private static final String DB_NAME = "order.db";

    private static final SortedMap<Integer, Migration> ALL_MIGRATIONS = new TreeMap<>();

    static {
        ALL_MIGRATIONS.put(1, new V1Migration());
        //      ALL_MIGRATIONS.put(2, new V2Migration());
        //      ALL_MIGRATIONS.put(3, new V3Migration());
    }

    public OrderOpenHelper(Context context, SQLiteDatabase.CursorFactory factory) {
        super(context, DB_NAME, factory);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        super.onCreate(db);
        executeMigrations(db, ALL_MIGRATIONS.keySet());
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
        SortedMap<Integer, Migration> migrations = ALL_MIGRATIONS.subMap(oldVersion, newVersion);
        executeMigrations(sqLiteDatabase, migrations.keySet());

    }


    private void executeMigrations(final SQLiteDatabase paramSQLiteDatabase, final Set<Integer>
            migrationVersions) {
        for (final Integer version : migrationVersions) {
//          ALL_MIGRATIONS.get(version).migrate(paramSQLiteDatabase);
        }
    }
}

interface Migration {

    void migrate(SQLiteDatabase db);

}

class V1Migration implements Migration {
    @Override
    public void migrate(SQLiteDatabase db) {
        db.execSQL("ALTER TABLE NOTE ADD COLUMN test");
    }
}
  • Application类
public class MyApplication extends Application {
    private OrderOpenHelper mHelper;
    private SQLiteDatabase mDb;
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;

    @Override
    public void onCreate() {
        super.onCreate();
        initBoxService();
        mDDApplication = this;
        setDatabase();
        initCrashHandler();
    }

    private void initBoxService() {
        OkSocket.initialize(this,true);
        BoxService.startService(this);
    }

    private static MyApplication mDDApplication;

    /**
     * 获取Application对象
     *
     * @return DDApplication
     */
    public static MyApplication getInstance() {
        return mDDApplication;
    }

    /**
     * 设置greenDao
     */
    private void setDatabase() {
        mHelper = new OrderOpenHelper(this, null);
        mDb = mHelper.getWritableDatabase();
        mDaoMaster = new DaoMaster(mDb);
        mDaoSession = mDaoMaster.newSession();
    }

    public DaoSession getDaoSession() {
        return mDaoSession;
    }

    /**
     * Crash处理
     */
    private void initCrashHandler() {
        CrashHandler.getInstance().init(this);
    }
}
  • 第五步 对数据库进行增删查改
    获取对象
dao = MyApplication.getApplication().getDaoSession().getUserDao();

//增

private void insertData() { 
name = et_Name.getText().toString().trim();    
age = et_age.getText().toString();    
sex = et_sex.getText().toString().trim();    
salary = et_Salary.getText().toString().trim();    
User insertData = new User(null, name, age, sex, salary);    
dao.insert(insertData);
}

//删

private voiddeleteData(Long id){
userInfoDao.deleteByKey(id);
}

//改

private void updateData(int i) {    
name = et_Name.getText().toString().trim();    
age = et_age.getText().toString();    
sex = et_sex.getText().toString().trim();    
salary = et_Salary.getText().toString().trim();    
User updateData = new User(listsUser.get(i).getId(), name, age, sex, salary);    dao.update(updateData);
}

//查

private void queryData() {    
List<User> users = dao.loadAll();    
String userName = "";    
for (int i = 0; i < users.size(); i++) {        
userName += users.get(i).getName() + ",";    
}    
Toast.makeText(this, "查询全部数据==>" + userName, Toast.LENGTH_SHORT).show();
}
  • 执行自定义sql 语句
String sql ="insert into user values (null,'111')";
 AFaApplication.getApplication().getDaoSession().getDatabase().execSQL(sql)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值