GreenDao是一个将对象映射到SQLite数据库中的轻量且快速的ORM(对象关系映射)解决方案
它分装了一些SQL语法,可以方便的增加,删除,修改和简单查询。但是不可以进行过于复杂的查询,例如,多表联合查询。
它的基本使用方式如下
首先要导入依赖,在app.gradle下
apply plugin: 'org.greenrobot.greendao'
compile 'org.greenrobot:greendao:3.2.0'
compile 'org.greenrobot:greendao-generator:3.2.2'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
android目录下
greendao {
//数据库的schema版本,也可以理解为数据库版本号
schemaVersion 1
//设置DaoMaster、DaoSession、Dao包名,也就是要放置这些类的包的全路径。
daoPackage 'zjc.com.greendao_text'
//设置DaoMaster、DaoSession、Dao目录
targetGenDir 'src/main/java'
}
在工程.gradle下
repositories {
mavenCentral()
}
dependencies {
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1'
}
好了,以上是配置GreenDao环境和依赖
下面的生成也很简单
首先创建一个GreenDao实体类。例如我创建的User.class 它是采用注解的方式创建数据库、数据表里面的字段,在这里ID最好
写成Long类型(long包装类)。因为一般情况下,id是主键自增的,在传值的过程中,不需要赋值。如果是long类型,就必须要手动赋值,否则有可能会出现id重复的错误,所以写成Long类型,传值传null就可以。
注意:一定要注意,在你的类上面加上@Entity注解,否则这个实体类无效
@Entity
public class User {
@Id(autoincrement = true)
private Long _id;
private String userName;
private String age;
private String sex;
}
然后点击Make Project 加载一下工程
你会发现你的实体类变成下面这样了
@Entity
public class User {
//创建SQL数据库ID (autoincrement = true)意思是主键自增 这里ID类型最好写成Long(long的包装类) 类型而不写成long,否则可能会出现ID重复的问题
@Id(autoincrement = true)
private Long _id;
private String userName;
private String age;
private String sex;
//----------------------------下面都是自动生成的-------------------华丽丽的分割线----------------------
@Generated(hash = 1594422790)
public User(Long _id, String userName, String age, String sex) {
this._id = _id;
this.userName = userName;
this.age = age;
this.sex = sex;
}
@Generated(hash = 586692638)
public User() {
}
public Long get_id() {
return this._id;
}
public void set_id(Long _id) {
this._id = _id;
}
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getAge() {
return this.age;
}
public void setAge(String age) {
this.age = age;
}
public String getSex() {
return this.sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
这时,你会惊喜的发现,在你的包中多了这三个类
最后一个XXXDao是根据你定义的实体类的名字进行命名的
然后,你就可以开始风骚的写代码了,嘎嘎嘎
当然,在开始写代码之前,你还需要初始化一下你的GreenDao
在Application里面写
public class MyApp extends Application {
private static MyApp myApp;
private DaoMaster.DevOpenHelper devOpenHelper;
private SQLiteDatabase db;
private DaoMaster daoMaster;
private DaoSession session;
@Override
public void onCreate() {
super.onCreate();
myApp = this;
setDatabase();
}
/**
* 单例模式
* @return
*/
public static MyApp getMyApp(){
return myApp;
}
private void setDatabase() {
//获取数据库帮助类创建数据表
devOpenHelper = new DaoMaster.DevOpenHelper(this, "Users.db", null);
db = devOpenHelper.getWritableDatabase();
daoMaster = new DaoMaster(db);
session = daoMaster.newSession();
}
/**
* 重点类 用来返回获取数据库对象
* @return
*/
public DaoSession getDaoSession() {
return session;
}
public SQLiteDatabase getDb() {
return db;
}
}
初始化完毕后,最好写一个工具类方便使用
public class GreenDaoUtils {
private static final String TAG = "GreenDaoUtils";
private static GreenDaoUtils greenDaoUtils = null;
private final DaoSession daoSession;
/**
* 单例模式
*
* @return
*/
public static GreenDaoUtils getGreenDaoUtils() {
if (greenDaoUtils == null) {
greenDaoUtils = new GreenDaoUtils();
}
return greenDaoUtils;
}
/**
* 构造方法初始化
*/
public GreenDaoUtils() {
MyApp myApp = MyApp.getMyApp();
daoSession = myApp.getDaoSession();
}
/**
* 添加
*
* @param user
*/
public void insert(User user) {
daoSession.insert(user);
//关闭
daoSessionClear();
}
/**
* 根据姓名进行修改
* @param user
*/
public void updateInName(User user,String name) {
//得到数据库对象
UserDao userDao = daoSession.getUserDao();
Log.d(TAG, "updateInName: ==="+name);
//在修改之前先进行条件查询
List<User> list = userDao.queryBuilder().where(UserDao.Properties.UserName.like(name)).build().list();
Log.d(TAG, "updateInName: "+list.size());
for (int i = 0; i < list.size(); i++) {
Log.d(TAG, "updateInName: name=="+user.getUserName()+"++age="+user.getAge()+"++sex="+user.getSex());
Log.d(TAG, "updateInName: name=="+list.get(i).getUserName());
Log.d(TAG, "updateInName1: name=="+user.getUserName()+"++age="+user.getAge()+"++sex="+user.getSex());
list.get(i).setUserName(user.getUserName());
list.get(i).setSex(user.getSex());
list.get(i).setAge(user.getAge());
//修改
userDao.update(list.get(i));
Log.d(TAG, "updateInName2: name=="+user.getUserName()+"++age="+user.getAge()+"++sex="+user.getSex());
}
//关闭
daoSessionClear();
}
/**
* 全部删除
*/
public void deleteAll() {
UserDao userDao = daoSession.getUserDao();
userDao.deleteAll();
//关闭
daoSessionClear();
}
/**
* 根据姓名删除
*
* @param name
*/
public void deleteName(String name) {
UserDao userDao = daoSession.getUserDao();
List<User> list = userDao.queryBuilder().where(UserDao.Properties.UserName.like(name)).build().list();
for (int i = 0; i < list.size(); i++) {
userDao.delete(list.get(i));
}
//关闭
daoSessionClear();
}
/**
* 查询全部
*
* @return
*/
public List<User> queryAll() {
UserDao userDao = daoSession.getUserDao();
List<User> list = userDao.queryBuilder().build().list();
//关闭
daoSessionClear();
return list;
}
/**
* 根据ID查询
*
* @param id
* @return
*/
public List<User> queryID(int id) {
UserDao userDao = daoSession.getUserDao();
List<User> list = userDao.queryBuilder().where(UserDao.Properties._id.like("" + id)).build().list();
//关闭
daoSessionClear();
return list;
}
/**
* 根据姓名查询
*
* @param userName
* @return
*/
public List<User> queryUserName(String userName) {
UserDao userDao = daoSession.getUserDao();
List<User> list = userDao.queryBuilder().where(UserDao.Properties.UserName.like("%" + userName + "%")).build().list();
//关闭
daoSessionClear();
return list;
}
/**
* 关闭
*/
public void daoSessionClear() {
daoSession.clear();
}
}
使用方式,比较简单的一种方式我使用的是点击事件
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.add:
//添加
String name = edit_name.getText().toString();
String ageStr = edit_age.getText().toString();
String sex = edit_sex.getText().toString();
user.set_id(null);
user.setAge(ageStr);
user.setSex(sex);
user.setUserName(name);
Log.d(TAG, "onClick:_id"+user.get_id()+" name="+user.getUserName()+"++age="+user.getAge()+"+sex="+user.getSex()+"");
//添加
greenDaoUtils.insert(user);
List<User> list = greenDaoUtils.queryAll();
adapter = new MyAdapter(this,list);
listView.setAdapter(adapter);
break;
case R.id.delete:
//删除
//调用弹出框
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("删除");
View view = View.inflate(this, R.layout.alertdialog_item, null);
builder.setView(view);
builder.setCancelable(true);
final EditText alert_name = view.findViewById(R.id.alert_name);
//删除按钮
builder.setPositiveButton("删除", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String name = alert_name.getText().toString();
//删除
greenDaoUtils.deleteName(name);
List<User> users = greenDaoUtils.queryAll();
adapter = new MyAdapter(MainActivity.this,users);
listView.setAdapter(adapter);
}
});
//取消删除按钮
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "你点击了取消", Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
break;
case R.id.update:
//修改
//修改弹出框
AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
builder1.setTitle("修改");
View view1 = View.inflate(this, R.layout.alertdialog_item_update, null);
final EditText alert_update = view1.findViewById(R.id.alert_update);
builder1.setView(view1);
builder1.setCancelable(true);
//修改按钮
builder1.setPositiveButton("确认修改", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog.Builder builder2 = new AlertDialog.Builder(MainActivity.this);
final String updatesName = alert_update.getText().toString();
View view2 = View.inflate(MainActivity.this, R.layout.alertdialog_item_update_i, null);
final EditText alert_update_name = view2.findViewById(R.id.alert_update_name);
final EditText alert_update_age = view2.findViewById(R.id.alert_update_age);
final EditText alert_update_sex = view2.findViewById(R.id.alert_update_sex);
builder2.setTitle("确认修改");
builder2.setView(view2);
builder2.setCancelable(true);
builder2.setPositiveButton("修改", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String name = alert_update_name.getText().toString();
String age = alert_update_age.getText().toString();
String sex = alert_update_sex.getText().toString();
User user = new User();
user.setUserName(name);
user.setAge(age);
user.setSex(sex);
Log.d(TAG, "onClick:======== "+name);
greenDaoUtils.updateInName(user,updatesName);
List<User> users = greenDaoUtils.queryAll();
adapter = new MyAdapter(MainActivity.this,users);
listView.setAdapter(adapter);
}
});
builder2.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "你点击了取消", Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog2 = builder2.create();
alertDialog2.show();
}
});
builder1.setNegativeButton("取消修改", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "你取消了修改", Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog1 = builder1.create();
alertDialog1.show();
break;
case R.id.query:
//查询
List<User> list1 = greenDaoUtils.queryAll();
adapter = new MyAdapter(this,list1);
listView.setAdapter(adapter);
break;
}
}
好啦是不是很简单