集成
// In your root build.gradle file:
buildscript {
repositories {
jcenter()
mavenCentral() // add repository
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.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 {
implementation 'org.greenrobot:greendao:3.2.2' // add library
}
greendao {
//数据库版本号
schemaVersion 1
//设置DaoMaster、DaoSession、Dao包名,也就是要放置这些类的包的路径。
daoPackage 'com.yechaoa.test.dao'
//设置DaoMaster、DaoSession、Dao目录
targetGenDir 'src/main/java'
}
常用注解
- @Id(autoincrement = true) 主键自增长
- @NotNull 不为空
- @OrderBy(asc desc) 排序
- @Transient 短暂的,不会持久化,表示实体类中普通的字段
- @Property 参数 字段
- @Unique 唯一约束
- @ToOne 一对一,定义到另一个实体对象的关系,应在持有目标实体对象的字段上使用该注解
- @ToMany 一对多,使用@ToMany的属性代表目标实体的List,集合里的对象都必须至少有一个属性指向拥有@ToMany的实体
- @JoinEntity 多对多,如果两个实体是多对多的关系,那么需要第三张表(表示两个实体关系的表)
常用的SQL语句条件关键词
- eq():==
- noteq():!=
- orderAsc:升序排序
- orderDesc: 降序排序
- gt(): >
- t():<
- ge:>=
- le:<=
- like():包含
- between:俩者之间
- in:在某个值内
- notIn:不在某个值内
- limit(int): 限制查询的数量
- list() 返回一个集合
- listLazy() 懒查询
新建一个实体类
@Entity
public class OrderDB {
@Id(autoincrement = true)
private Long id;
@NotNull
private Integer price;
private String name;
private String num;
....
}
然后编译会在自定义的文件夹包名(比如上面的‘com.yechaoa.test.dao’)下生成3个文件:
- DaoMaster
- DaoSession
- OrderDBDao
编写OrderDaoManager类
单例保证唯一性,统一入口
/**
* Created by yechaoa on 2018/10/29.
* Describe :
*/
public class OrderDaoManager {
private static final String DB_NAME = "order_db";
private Context context;
@SuppressLint("StaticFieldLeak")
private volatile static OrderDaoManager manager = new OrderDaoManager();
private static DaoMaster sDaoMaster;
@SuppressLint("StaticFieldLeak")
private static DaoMaster.DevOpenHelper sHelper;
private static DaoSession sDaoSession;
/**
* 单例模式获得操作数据库对象
*/
public static OrderDaoManager getInstance() {
return manager;
}
public void init(Context context) {
this.context = context;
}
/**
* 判断是否有存在数据库,如果没有则创建
*/
private DaoMaster getDaoMaster() {
if (sDaoMaster == null) {
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, DB_NAME, null);
sDaoMaster = new DaoMaster(helper.getWritableDatabase());
}
return sDaoMaster;
}
/**
* 完成对数据库的添加、删除、修改、查询操作
*/
public DaoSession getDaoSession() {
if (sDaoSession == null) {
if (sDaoMaster == null) {
sDaoMaster = getDaoMaster();
}
sDaoSession = sDaoMaster.newSession();
}
return sDaoSession;
}
/**
* 关闭所有的操作,数据库开启后,使用完毕要关闭
*/
public void closeConnection() {
closeHelper();
closeDaoSession();
}
private void closeHelper() {
if (sHelper != null) {
sHelper.close();
sHelper = null;
}
}
private void closeDaoSession() {
if (sDaoSession != null) {
sDaoSession.clear();
sDaoSession = null;
}
}
}
编写OrderDBHelper类,处理增删改查
/**
* Created by yechao on 2018/10/29.
* Describe :
*/
public class OrderDBHelper {
private OrderDaoManager mManager;
public OrderDBHelper(Context context) {
mManager = OrderDaoManager.getInstance();
mManager.init(context);
}
/**
* 插入单条数据,如果表未创建,先创建OrderDB表
*/
public boolean insertOrderDB(OrderDB o) {
boolean flag;
flag = mManager.getDaoSession().getOrderDBDao().insert(o) != -1;
return flag;
}
/**
* 插入多条数据,在子线程操作
*/
public boolean insertMultiOrderDB(final List<OrderDB> oList) {
boolean flag = false;
try {
mManager.getDaoSession().runInTx(new Runnable() {
@Override
public void run() {
for (OrderDB o : oList) {
mManager.getDaoSession().insertOrReplace(o);
}
}
});
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/**
* 修改一条数据
*/
public boolean updateOrderDB(OrderDB o) {
boolean flag = false;
try {
mManager.getDaoSession().update(o);
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/**
* 删除单条记录
*/
public boolean deleteOrderDB(OrderDB o) {
boolean flag = false;
try {
mManager.getDaoSession().delete(o);
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/**
* 删除所有记录
*/
public boolean deleteAll() {
boolean flag = false;
try {
mManager.getDaoSession().deleteAll(OrderDB.class);
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/**
* 查询所有记录
*/
public List<OrderDB> queryAllOrderDB() {
return mManager.getDaoSession().loadAll(OrderDB.class);
}
/**
* 根据主键id查询记录
*/
public OrderDB queryOrderDBById(long key) {
return mManager.getDaoSession().load(OrderDB.class, key);
}
/**
* 使用native sql进行查询操作
*/
public List<OrderDB> queryOrderDBByNativeSql(String sql, String[] conditions) {
return mManager.getDaoSession().queryRaw(OrderDB.class, sql, conditions);
}
/**
* 使用queryBuilder进行查询
*/
public List<OrderDB> queryOrderDBByQueryBuilder(long id) {
QueryBuilder<OrderDB> queryBuilder = mManager.getDaoSession().queryBuilder(OrderDB.class);
return queryBuilder.where(OrderDBDao.Properties.Id.eq(id)).list();
}
/**
* orderAsc:升序排序 orderDesc: 降序排序
*/
public List<OrderDB> queryOrderDBByQueryBuilder2(Integer price, String name) {
QueryBuilder<OrderDB> queryBuilder = mManager.getDaoSession().queryBuilder(OrderDB.class);
return queryBuilder
.where(OrderDBDao.Properties.Price.eq(price),
OrderDBDao.Properties.Name.eq(name))
.orderAsc(OrderDBDao.Properties.StatusId)
.list();
}
/**
* 模糊查找 关键词需要前后加上%
*/
public List<OrderDB> queryOrderDBByQueryBuilderSearch(String key) {
QueryBuilder<OrderDB> queryBuilder = mManager.getDaoSession().queryBuilder(OrderDB.class);
return queryBuilder
.where(OrderDBDao.Properties.Name.like("%" + key + "%"))
.orderAsc(OrderDBDao.Properties.StatusId)
.list();
}
}
使用
先初始化help对象
mOrderDBHelper = new OrderDBHelper(PickActivity.this);
插入多条
mOrderDBS = new ArrayList<>();
mOrderDBHelper = new OrderDBHelper(this);
for (int i = 0; i < mList.size(); i++) {
mOrderDBS.add(new OrderDB(null, mDate,mList.get(i).price,, mDate,mList.get(i).name, i, ...));
}
mOrderDBHelper.insertMultiOrderDB(mOrderDBS);
查询单条
Long id = mOrderDBS.get(pos).getId();
OrderDB orderDB1 = mOrderDBHelper.queryOrderDBById(id);
根据条件查询
mOrderDBS = (ArrayList<OrderDB>) mOrderDBHelper.queryOrderDBByQueryBuilder2(mPrice, mName);
更新单条
Long id = mOrderDBS.get(pos).getId();
OrderDB orderDB1 = mOrderDBHelper.queryOrderDBById(id);
orderDB1.setName("测试");
mOrderDBHelper.updateOrderDB(orderDB1);
模糊查找
mOrderDBS = (ArrayList<OrderDB>) mOrderDBHelper.queryOrderDBByQueryBuilderSearch(searchText);
删除所有
mOrderDBHelper.deleteAll();
记得释放资源
@Override
protected void onDestroy() {
super.onDestroy();
//关闭资源
OrderDaoManager.getInstance().closeConnection();
}
数据库升级
- 修改版本号,即
schemaVersion 1
- 修改实体类
然后编译即可。
特殊情况
自定义DBHelper,继承DaoMaster.OpenHelper
public class DBHelper extends DaoMaster.OpenHelper {
public static final String DBNAME = "lenve.db";
public DBHelper(Context context) {
super(context, DBNAME, null);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
super.onUpgrade(db, oldVersion, newVersion);
}
}
在onUpgrade
方法中处理
然后数据库的初始化也需要重新处理
DBHelper devOpenHelper = new DBHelper(this);
DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDb());
DaoSession daoSession = daoMaster.newSession();
userDao = daoSession.getUserDao();
主要是 增删改查
操作和一些SQL语句
的应用
来源:CSDN
作者:呆木弱鸡
链接:https://blog.csdn.net/qq_29034779/article/details/103687220