参考:
https://www.jianshu.com/p/14fbf995e51e
https://www.jianshu.com/p/39db996be365
1.简介
Android开发中我们或多或少都会接触到数据库。Android中提供了一个占用内存极小的关系型数据库-SQLite。虽然Android系统中提供了许多操作SQLite的API,但是我们还是需要手动去编写SQL语句,这经常会出现一些莫名其妙的问题(😂,不要问我为什么)。所以便出现了许多ORM(对象关系映射)框架。其中比较著名的有GreenDao、OrmLite、Litepal等。
GreenDAO是一个开源的Android ORM(“对象/关系映射”),通过ORM(称为“对象/关系映射”),在我们数据库开发过程中节省了开发时间!
gitHub 地址:https://github.com/lyyRunning/greenDao
2.GreenDao的官方文档
- GreenDao:适用于您的SQLite数据库的Android ORM
- GreenDao的github地址
- GreenDao的Google讨论区
- GreenDao 加密SQLCipher for Android官方说明地址
- GreenDao使用文档
- GreenDao 升级文档
3.GreenDao的使用
GreenDao的核心类有三个:分别是DaoMaster,DaoSession,XXXDao,这三个类都会自动创建,无需自己编写创建!
1.DaoMaster:DaoMaster保存数据库对象(SQLiteDatabase)并管理特定模式的DAO类(而不是对象)。它有静态方法来创建表或删除它们。它的内部类OpenHelper和DevOpenHelper是SQLiteOpenHelper实现,它们在SQLite数据库中创建模式。
2.DaoSession:管理特定模式的所有可用DAO对象,您可以使用其中一个getter方法获取该对象。DaoSession还提供了一些通用的持久性方法,如实体的插入,加载,更新,刷新和删除。
3.XXXDao:数据访问对象(DAO)持久存在并查询实体。对于每个实体,greenDAO生成DAO。它具有比DaoSession更多的持久性方法,例如:count,loadAll和insertInTx。
Entities :可持久化对象。通常, 实体对象代表一个数据库行使用标准 Java 属性(如一个POJO 或 JavaBean )。
(1)导入Gradle插件和Dao代码生成
buildscript {
repositories {
google()
jcenter()
//添加
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0'
//greendao
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'
classpath 'com.jakewharton:butterknife-gradle-plugin:8.5.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
//添加
maven { url "https://jitpack.io" }
}
}
(2)配置相关依赖
// 在 Moudle:app的 build.gradle 文件中添加:
plugins {
id 'com.android.application'
}
apply plugin: 'org.greenrobot.greendao' // apply plugin
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.wfx.greendaodemo"
minSdkVersion 18
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
greendao{
schemaVersion 1
daoPackage 'com.greendao.gen'
targetGenDir 'src/main/java'
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'com.google.android.material:material:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'org.greenrobot:greendao:3.3.0' // add library
}
(3)配置数据库相关信息
greendao {
//数据库版本号
schemaVersion 1
// 设置DaoMaster、DaoSession、Dao 包名
daoPackage 'com.greendao.gen'
//设置DaoMaster、DaoSession、Dao目录,请注意,这里路径用.不要用
targetGenDir 'src/main/java'
//设置为true以自动生成单元测试。
generateTests false
//应存储生成的单元测试的基本目录。默认为 src / androidTest / java。
targetGenDirTests 'src/main/java'
}
配置完成,在Android Studio中使用Build> Make Project,重写build项目,GreenDao集成完成!
(4)创建存储对象实体类(get,set build会自动生产)
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Generated;
@Entity
public class User {
@Id(autoincrement = true) //设置自增长
private Long id;
private String name;
private int age;
@Generated(hash = 1309193360)
public User(Long id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
@Generated(hash = 586692638)
public User() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
(5)创建类成功后,build一下,自动生成DaoMaster,DaoSession,UserDao
image.png(6)创建一个UserDBManager
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.greendao.gen.DaoMaster;
import com.greendao.gen.DaoSession;
import com.greendao.gen.UserDao;
import com.wfx.greendaodemo.entity.User;
import org.greenrobot.greendao.query.QueryBuilder;
import java.util.List;
public class UserDBManager {
private final static String dbName = "test_user_db";
private static UserDBManager mInstance;
private DaoMaster.DevOpenHelper openHelper;
private Context context;
public UserDBManager(Context context) {
this.context = context;
openHelper = new DaoMaster.DevOpenHelper(context, dbName, null);
}
/**
* 获取单例引用
*
* @param context
* @return
*/
public static UserDBManager getInstance(Context context) {
if (mInstance == null) {
synchronized (UserDBManager.class) {
if (mInstance == null) {
mInstance = new UserDBManager(context);
}
}
}
return mInstance;
}
/**
* 获取可读数据库
*/
private SQLiteDatabase getReadableDatabase() {
if (openHelper == null) {
openHelper = new DaoMaster.DevOpenHelper(context, dbName, null);
}
SQLiteDatabase db = openHelper.getReadableDatabase();
return db;
}
/**
* 获取可写数据库
*/
private SQLiteDatabase getWritableDatabase() {
if (openHelper == null) {
openHelper = new DaoMaster.DevOpenHelper(context, dbName, null);
}
SQLiteDatabase db = openHelper.getWritableDatabase();
return db;
}
/**
* 插入一条记录
*
* @param user
*/
public void insertUser(User user) {
DaoMaster daoMaster = new DaoMaster(getWritableDatabase());
DaoSession daoSession = daoMaster.newSession();
UserDao userDao = daoSession.getUserDao();
userDao.insert(user);
}
/**
* 插入用户集合
*
* @param users
*/
public void insertUserList(List<User> users) {
if (users == null || users.isEmpty()) {
return;
}
DaoMaster daoMaster = new DaoMaster(getWritableDatabase());
DaoSession daoSession = daoMaster.newSession();
UserDao userDao = daoSession.getUserDao();
userDao.insertInTx(users);
}
/**
* 删除一条记录
*
* @param user
*/
public void deleteUser(User user) {
DaoMaster daoMaster = new DaoMaster(getWritableDatabase());
DaoSession daoSession = daoMaster.newSession();
UserDao userDao = daoSession.getUserDao();
userDao.delete(user);
}
/**
* 更新一条记录
*
* @param user
*/
public void updateUser(User user) {
DaoMaster daoMaster = new DaoMaster(getWritableDatabase());
DaoSession daoSession = daoMaster.newSession();
UserDao userDao = daoSession.getUserDao();
userDao.update(user);
}
/**
* 查询用户列表
*/
public List<User> queryUserList() {
DaoMaster daoMaster = new DaoMaster(getReadableDatabase());
DaoSession daoSession = daoMaster.newSession();
UserDao userDao = daoSession.getUserDao();
QueryBuilder<User> qb = userDao.queryBuilder();
List<User> list = qb.list();
return list;
}
/**
* 查询用户列表
*/
public List<User> queryUserList(int age) {
DaoMaster daoMaster = new DaoMaster(getReadableDatabase());
DaoSession daoSession = daoMaster.newSession();
UserDao userDao = daoSession.getUserDao();
QueryBuilder<User> qb = userDao.queryBuilder();
qb.where(UserDao.Properties.Age.gt(age)).orderAsc(UserDao.Properties.Age);
List<User> list = qb.list();
return list;
}
}
(7)测试调用
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.wfx.greendaodemo.db.UserDBManager;
import com.wfx.greendaodemo.entity.User;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private String TAG = "GreenDaoDemo_TAG";
private UserDBManager dbManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbManager = UserDBManager.getInstance(this);
}
public void btn_add(View view){
for (int i = 0; i < 5; i++) {
User user = new User();
user.setAge(i * 3);
user.setName("第" + i + "人");
dbManager.insertUser(user);
}
}
public void btn_delete(View view){
List<User> userList = dbManager.queryUserList();
for (User user: userList) {
if(user.getId() == 0){
Log.e(TAG, "btn_delete: 删除数据 :" + user.toString() );
dbManager.deleteUser(user);
}
}
Log.e(TAG, "--------------------------------------------------------" );
List<User> userList2 = dbManager.queryUserList();
for (User user:userList2) {
Log.e(TAG, "btn_delete: " + user.toString());
}
}
public void btn_change(View view){
List<User> userList = dbManager.queryUserList();
for (User user: userList) {
if(user.getId() == 3){
Log.e(TAG, "btn_change: 更新user " + user.toString() );
user.setName("被更新了");
dbManager.updateUser(user);
}
}
Log.e(TAG, "btn_change: --------------------------------------------" );
List<User> userList2 = dbManager.queryUserList();
for (User user:userList2) {
Log.e(TAG, "btn_change: " + user.toString());
}
}
public void btn_select(View view){
List<User> userList = dbManager.queryUserList();
for (User user: userList) {
Log.e(TAG, "btn_select: " + user.toString());
}
}
}
4.GreenDao的常用注解
实体@Entity注解
schema:告知GreenDao当前实体属于哪个schema
active:标记一个实体处于活跃状态,活动实体有更新、删除和刷新方法
nameInDb:在数据库中使用的别名,默认使用的是实体的类名
indexes:定义索引,可以跨越多个列
createInDb:标记创建数据库表
基础属性注解
@Id:主键 Long 型,可以通过@Id(autoincrement = true)设置自增长
@Property:设置一个非默认关系映射所对应的列名,默认是使用字段名,例如:@Property(nameInDb = "name")
@NotNull:设置数据库表当前列不能为空
@Transient:添加此标记后不会生成数据库表的列
索引注解
@Index:使用@Index作为一个属性来创建一个索引,通过name设置索引别名,也可以通过unique给索引添加约束
@Unique:向数据库添加了一个唯一的约束
关系注解
@ToOne:定义与另一个实体(一个实体对象)的关系
@ToMany:定义与多个实体对象的关系
5.一些查询条件关键字:
eq():"equal ('=?')" 等于;
notEq() :"not equal ('<>?')" 不等于;
like():" LIKE ?" 值等于;
between():" BETWEEN ? AND ?" 取中间范围;
in():" IN (" in命令;
notIn():" NOT IN (" not in 命令;
gt():">?" 大于;
lt():"<? " 小于;
ge():">=?" 大于等于;
le():"<=? " 小于等于;
isNull():" IS NULL" 为空;
isNotNull():" IS NOT NULL" 不为空;
网友评论