@linux1s1s
2016-12-01T10:26:28.000000Z
字数 6853
阅读 1875
AndroidRefine
2016-11
下面以一个简单的Demo演示一下如何使用GreenDAO
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="okhttp.mutex.com.orm_demo">
<application
android:name=".ORMApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.2'
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao'
android {
compileSdkVersion 24
buildToolsVersion "24.0.0"
defaultConfig {
applicationId "okhttp.mutex.com.orm_demo"
minSdkVersion 15
targetSdkVersion 24
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
greendao{
schemaVersion 1
daoPackage 'com.admom.mygreendaotest'
targetGenDir 'src/main/java'
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:24.2.1'
testCompile 'junit:junit:4.12'
compile 'org.greenrobot:greendao:3.2.0'
}
以上配置重点关注一下信息:
- 加入greendao插件
- 配置greendao生成代码的目录地址,包名以及版本号
- 配置greendao的依赖地址
另外以上配置greendao信息的相关字段简要说明如下:
- schemaVersion: 数据库schema版本,也可以理解为数据库版本号
- daoPackage:设置DaoMaster 、DaoSession、Dao包名
- targetGenDir:设置DaoMaster 、DaoSession、Dao目录
- targetGenDirTest:设置生成单元测试目录
- generateTests:设置自动生成单元测试用例
先生成POJO类,greendao通过注解的形式自动生成DAO类
package okhttp.mutex.com.orm_demo;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Generated;
@Entity
public class Info {
@Id(autoincrement = true)
private long id;
private String name;
private int age;
...
}
编译完以后会自动生成DaoMaster
, DaoSession
, XXXDao
等类,并把这些类自动放到指定的目录和包名下,如图所示:
我们需要进一步了解注解的相关意思
- 实体@Entity注解
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:定义与多个实体对象的关系
package okhttp.mutex.com.orm_demo;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.admom.mygreendaotest.DaoMaster;
public class GreenDAOManager {
private static GreenDAOManager sINSTANCE;
private final DaoMaster.DevOpenHelper mHelper;
private GreenDAOManager(Context context, String name) {
mHelper = new DaoMaster.DevOpenHelper(context, name, null);
}
public static void createInstance(Context context, String name) {
if (sINSTANCE == null) {
synchronized (GreenDAOManager.class) {
if (sINSTANCE == null) {
sINSTANCE = new GreenDAOManager(context, name);
}
}
}
}
public static GreenDAOManager getInstance() {
return sINSTANCE;
}
public SQLiteDatabase getReadableDatabase() {
return mHelper.getReadableDatabase();
}
public SQLiteDatabase getWritableDatabase() {
return mHelper.getWritableDatabase();
}
}
package okhttp.mutex.com.orm_demo;
import com.admom.mygreendaotest.DaoMaster;
import com.admom.mygreendaotest.DaoSession;
import com.admom.mygreendaotest.InfoDao;
import org.greenrobot.greendao.query.QueryBuilder;
import java.util.List;
public class InfoDAOHelper {
private InfoDAOHelper() {
//Do Nothing
}
/**
* 插入一条数据
*
* @param info
*/
public static void insertInfo(Info info) {
if (info == null)
return;
InfoDao infoDao = obtainWritableInfoDao();
infoDao.insert(info);
}
/**
* 插入一组数据
*
* @param infoList
*/
public static void insertInfo(List<Info> infoList) {
if (infoList == null || infoList.isEmpty())
return;
InfoDao info = obtainWritableInfoDao();
info.insertInTx(infoList);
}
/**
* 删除一组数据
*
* @param info
*/
public static void deleteInfo(Info info) {
if (info == null)
return;
InfoDao dao = obtainWritableInfoDao();
dao.delete(info);
}
/**
* 更新一组数据
*
* @param info
*/
public static void update(Info info) {
if (info == null)
return;
InfoDao dao = obtainWritableInfoDao();
dao.update(info);
}
/**
* 查询数据列表
*
* @return
*/
public static List<Info> queryInfoList() {
InfoDao dao = obtainReadableInfoDao();
QueryBuilder<Info> builder = dao.queryBuilder();
return builder.list();
}
/**
* 查询符合条件的数据列表
*
* @param age
* @return
*/
public static List<Info> queryInfoList(int age) {
InfoDao dao = obtainReadableInfoDao();
QueryBuilder<Info> builder = dao.queryBuilder();
builder.where(InfoDao.Properties.Age.eq(age)).orderAsc(InfoDao.Properties.Age);
return builder.list();
}
private static InfoDao obtainWritableInfoDao() {
DaoMaster master = new DaoMaster(GreenDAOManager.getInstance().getWritableDatabase());
DaoSession session = master.newSession();
return session.getInfoDao();
}
private static InfoDao obtainReadableInfoDao() {
DaoMaster master = new DaoMaster(GreenDAOManager.getInstance().getReadableDatabase());
DaoSession session = master.newSession();
return session.getInfoDao();
}
}
package okhttp.mutex.com.orm_demo;
import android.app.Application;
public class ORMApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
GreenDAOManager.createInstance(this, "db_test_name_4");
}
}
package okhttp.mutex.com.orm_demo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import java.util.List;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initInfo();
queryOri();
queryOri(21);
updateOri();
deleteOri();
}
private void updateOri() {
Info info = new Info(1, "name" + 1, 2 + 20);
InfoDAOHelper.update(info);
queryOri(22);
}
private void deleteOri() {
Info info = new Info(1, "name" + 1, 1 + 20);
InfoDAOHelper.deleteInfo(info);
queryOri(21);
}
private void queryOri(int age) {
List<Info> list = InfoDAOHelper.queryInfoList(age);
for (Info info : list) {
Log.w("mutex", age + " is : " + info.toString());
}
}
private void queryOri() {
List<Info> list = InfoDAOHelper.queryInfoList();
for (Info info : list) {
Log.i("mutex", info.toString());
}
}
private void initInfo() {
for (int i = 0; i < 10; i++) {
Info info = new Info(i, "name" + i, i + 20);
InfoDAOHelper.insertInfo(info);
}
}
}
以上验证符合预期。
参考文章:
GreenDAO Website Github Doc Ori
OrmLite Website Github