个人记录 GreenDao

常用注解说明

@Entity 告诉greenDao该对象为实体类,只有被@Entity注解的Bean类才能被操作

@Id 对象Id,使用long/Long类型作为EntityId,否则报错(autoincrement = true)表示主键自动增长 建议使用Long包装类型

@Property 设置数据库使用的段名,如果不设置,则段名默认使用属性名

@NotNull 该列不能为空

@Transient 该列不会存入数据库字段中

@Unique 该属性值必须唯一

@Generated 编译生成的构造函数,方法等注释,提示构造函数,方法等不能修改

创建实体类

@Id(autoincrement = true)
    private Long id;
    @Property(nameInDb = "dbname")
    private String name;

    private int age;

    private String gender;

不支持char类型的属性

Make Project一下GreenDao自动生成代码

数据库初始化

private void initData(Context context){
        //创建数据库,mStu.db
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context,"mStu.db");
        //获取可写数据库
        SQLiteDatabase db = helper.getWritableDatabase();
        //获取Dao管理者Session
        mSession = new DaoMaster(db).newSession();
        //获取Dao对象
        studentDao = mSession.getStudentDao();
    }

DevOpenHelper 用于创建SQlite数据库

DaoMaster GreenDao顶级对象,用于创建Session

Session 管理Dao对象

Dao对象 具有增删查改方法

以上是我个人的见解

初始化最好是在Application进行

public class MyApp extends Application {

    private StudentDao studentDao;
    private DatabaseManage databaseManage;

    @Override
    public void onCreate() {
        super.onCreate();
        if (databaseManage == null) {
            databaseManage = DatabaseManage.getInstance().init(this);
            studentDao = databaseManage.getStudentDao();
        }
    }

    public StudentDao getStudentDao() {
        return studentDao;
    }
}

猜你喜欢

转载自blog.csdn.net/NianandShao/article/details/81436129