GreenDAO 使用教程 GreenDao3.2.0使用教程
- 集成环境
// In your root build.gradle file: buildscript { repositories { jcenter() mavenCentral() // add repository } dependencies { classpath 'com.android.tools.build:gradle:2.3.1' classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin } } // In your app projects build.gradle file: apply plugin: 'com.android.application' apply plugin: 'org.greenrobot.greendao' // apply plugin dependencies { compile 'org.greenrobot:greendao:3.2.2' // add library }
- 在Gradle中配置数据库版本信息等
greendao { //当前数据库版本 schemaVersion 1 //由GreenDao自动生成代码所在的包名,默认的是在项目包下面新建一个gen。 daoPackage 'com.titan.data.greendao' //设置自动生成代码的目录 targetGenDir 'src/main/java' }
3.在项目中定义实体类
@Entity public class TrackPoint { @Id(autoincrement = true) private Long id; /**上传时间*/ @NotNull @Property(nameInDb = "TIME") private String time; /**经度*/ @Property(nameInDb = "LON") private double lon; /**纬度*/ @Property(nameInDb = "LAT") private double lat; /**用户id*/ @Property(nameInDb = "USERID") private String userid; }
注解:
@Entity 标识实体类,greenDAO会映射成sqlite的一个表,表名为实体类名的大写形式
@Id 标识主键,该字段的类型为long或Long类型,autoincrement设置是否自动增长
@Property 标识该属性在表中对应的列名称, nameInDb设置名称
@Transient 标识该属性将不会映射到表中,也就是没有这列
@NotNull 设置表中当前列的值不可为空
@Convert 指定自定义类型(@linkPropertyConverter)
@Generated greenDAO运行所产生的构造函数或者方法,被此标注的代码可以变更或者下次运行时清除
@Index 使用@Index作为一个属性来创建一个索引;定义多列索引(@link Entity#indexes())
@JoinEntity 定义表连接关系
@JoinProperty 定义名称和引用名称属性关系
@Keep 注解的代码段在GreenDao下次运行时保持不变
1.注解实体类:默认禁止修改此类
2.注解其他代码段,默认禁止修改注解的代码段
@OrderBy 指定排序
@ToMany 定义与多个实体对象的关系
@ToOne 定义与另一个实体(一个实体对象)的关系
@Unique 向数据库列添加了一个唯一的约束
4.生成相关代码
定义好了之后按ctrl+F9(或者工具栏build下面的Make Project)对项目进行重新构建,再 daoPackage的目录下就会自动生成代码
5.新建一个类,实例化greenDAO所需要的几个关键对象,DaoMaster,DaoSession,代码如下:
public class GreenDaoManager { private DaoMaster mDaoMaster; private DaoSession mDaoSession; private static volatile GreenDaoManager mInstance = null; private GreenDaoManager(){ if (mInstance == null) { DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(App.getContext(), "user.db"); mDaoMaster = new DaoMaster(devOpenHelper.getWritableDatabase()); mDaoSession = mDaoMaster.newSession(); } } public static GreenDaoManager getInstance() { if (mInstance == null) { synchronized (GreenDaoManager.class) { if (mInstance == null) { mInstance = new GreenDaoManager(); } } } return mInstance; } public DaoMaster getMaster() { return mDaoMaster; } public DaoSession getSession() { return mDaoSession; } public DaoSession getNewSession() { mDaoSession = mDaoMaster.newSession(); return mDaoSession; } }
6.然后在Application中初始化:
GreenDaoManager.getInstance();
7.数据库增、删、查、改
首先获得UserDao的对象
UserDao userDao=GreenDaoManager.getInstance().getNewSession().getUserDao();
增:
User user = new User(null, name, age, studentId); userDao.insert(user); insert(T entity) 当指定主键在表中存在时会发生异常 insertOrReplace(T entity) 当指定主键在表中存在时会覆盖数据 insertInTx(Iterableentities) 批量插入数据 </pre> s 删: ``` User user = new User(null, name, age, studentId); userDao.delete(user) delete(T entity) 删除数据 deleteByKey(K key) 指定主键删除数据 deleteInTx(Iterable entities) 批量删除数据 deleteByKeyInTx(Iterable keys) 批量按数据删除数据 deleteAll() 删除所有数据 ``` 改: ``` User user = new User(id, name, age, studentId); userDao.update(user); update(T entity) 修改数据,主键需相同 updateInTx(Iterable entities) 批量更新数据 ``` 查: userDao.load(id) load(K key) 根据id查找数据 loadByRowId(long rowId) 根据行号查找数据 loadAll() 查找全部数据 模糊查询 List pestList=DaoManager.getInstance(TitanApplication.dbpath).getNewSession().getPestDao().queryBuilder() .whereOr(PestDao.Properties.Cname.like("%"+keyword+"%")) .list(); 8.一对一、一对多关系 greenDAO目前只支持一对一和一对多关系,并不支持多对多关系 一对一: ``` private Long studentId; @ToOne(joinProperty = "studentId") private Studentstudent; ``` ``` @Generated(hash = 313494093) public Student getStudent() { Long __key = this.studentId; if (student__resolvedKey == null || !student__resolvedKey.equals(__key)) { final DaoSession daoSession = this.daoSession; if (daoSession == null) { throw new DaoException("Entity is detached from DAO context"); } StudentDao targetDao = daoSession.getStudentDao(); Student studentNew = targetDao.load(__key); synchronized (this) { student = studentNew; student__resolvedKey = __key; } } return student; } ``` 使用@ToOne标记,joinProperty指定一个字段,如果没有定义,会自动生成一个字段,get方法时自动生成的,使用@Generated标记,代表自动生成的,无需动代码。 一对多(有三种映射形式): ``` @ToMany(referencedJoinProperty = "teacherId") private List teacherList; ``` referencedJoinProperty:指定目标实体中与源实体相对应的外键。 ``` @ToMany(joinProperties = { @JoinProperty(name="studentTag",referencedName = "teacherTag") }) private List teacherList; ``` JoinProperty: 对于复杂一点的关系可以定义一组@JoinProperty注解。每个@JoinProperty注解都需要有源实体中的源属性和对应实体中的引用属性。 ``` @ToMany @JoinEntity( entity = Teacher.class, sourceProperty = "teacherId", targetProperty = "id" ) private List teacherList; ``` @JoinEntity:在做NM多对多映射的时候使用 9.数据库升级 数据库升级最麻烦的就是数据保存的问题,下面是数据库升级时执行的代码。 ``` /** WARNING: Drops all table on Upgrade! Use only during development. */ public static class DevOpenHelper extends OpenHelper { public DevOpenHelper(Context context, String name) { super(context, name); } public DevOpenHelper(Context context, String name, CursorFactory factory) { super(context, name, factory); } @Override public void onUpgrade(Database db, int oldVersion, int newVersion) { Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion + " by dropping all tables"); dropAllTables(db, true); onCreate(db); } } ``` 第一句注释的话已经告诉我们数据库升级时会删除所有的表,重新创建。所以我们可以自定义一个类继承OpenHelper,在升级时先生成临时表,删除旧表创建新表后,再把临时表的数据导入进去。有牛人已经做出这个项目来了,我就厚颜无耻选择直接用了。 在project的gradle添加 ``` allprojects { repositories { jcenter() maven { url "https://jitpack.io" } } } ``` 在app的gradle添加: ``` compile 'com.github.yuweiguocn:GreenDaoUpgradeHelper:v1.3.0' 注意:要是使用的还是greenDAO3.0以前的版本,添加的是 compile 'com.github.yuweiguocn:GreenDaoUpgradeHelper:v1.0.1' ``` 新建一个类 ``` public class MySQLiteOpenHelperextendsDaoMaster.OpenHelper{ public MySQLiteOpenHelper(Contextcontext,Stringname){ super(context,name); } public MySQLiteOpenHelper(Contextcontext,String name,SQLiteDatabase.CursorFactoryfactory) { super(context,name,factory); } @Override public void onUpgrade(SQLiteDatabasedb,int oldVersion,intnewVersion) { Log.d(“SQLite”,“数据库从”+oldVersion+“升级到”+newVersion); MigrationHelper.migrate(db,UserDao.class,StudentDao.class); } } ``` 在GreenDaoManager修改代码: ``` public class GreenDaoManager { private DaoMaster mDaoMaster; private DaoSession mDaoSession; private static volatile GreenDaoManager mInstance = null; private GreenDaoManager(){ if (mInstance == null) { //重写MySQLiteOpenHelper数据库升级,数据不丢失 //MyApplication.getContext()上下文表示了数据库存储路径为手机内存 //DEBUG表示是否打印debug MigrationHelper.DEBUG = true; MySQLiteOpenHelper helper = new MySQLiteOpenHelper(App.getContext(),"user.db",null); mDaoMaster = new DaoMaster(helper.getWritableDatabase()); mDaoSession = mDaoMaster.newSession(); } } public static GreenDaoManager getInstance() { if (mInstance == null) { synchronized (GreenDaoManager.class) { if (mInstance == null) { mInstance = new GreenDaoManager(); } } } return mInstance; } public DaoMaster getMaster() { return mDaoMaster; } public DaoSession getSession() { return mDaoSession; } public DaoSession getNewSession() { mDaoSession = mDaoMaster.newSession(); return mDaoSession; } } ``` 注意:migrate(SQLiteDatabase db, Class... daoClasses); 里面的参数是全部的实体类,就是要生成的表。 要生成的表。