欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Greendao的根据某个字段(非主键)插入去重以及根据某个字段删除对应的行条目

程序员文章站 2022-06-02 13:02:27
...

目前资料上greendao的删除基本都是根据主键删除的,如果我想通过里面一个字段比如name进行删除呢?下面是我对于全局搜索apk的一个greendao的小结。
1.删除某个字段的整条数据
简单封装下Greendao:

GreendaoUtil.java

public class GreendaoUtil {

    private volatile static GreendaoUtil ourInstance;

    private static String name = "search_history";

    public static final String SQL_DISTINCT_ENAME = "SELECT DISTINCT " + SearchHistoryDao.Properties.Text.columnName + " FROM " + SearchHistoryDao.TABLENAME;

    public static final String SQL_Delete = "DELETE FROM " + SearchHistoryDao.TABLENAME + " where text = ";

    private Context mContetx;
    private final DaoMaster mDaoMaster;
    private final DaoSession mDaoSession;

    public static GreendaoUtil getInstance() {
        if (null == ourInstance) {
            synchronized (GreendaoUtil.class) {
                if (null == ourInstance) {
                    ourInstance = new GreendaoUtil();
                }
            }
        }
        return ourInstance;
    }

    private GreendaoUtil() {
        this.mContetx = ZSApplication.getAppContext();
        MySQLiteOpenHelper mySQLiteOpenHelper = new MySQLiteOpenHelper(mContetx, name, null);
        mDaoMaster = new DaoMaster(mySQLiteOpenHelper.getWritableDatabase());
        mDaoSession = mDaoMaster.newSession();
    }

    public DaoMaster getmDaoMaster() {
        return mDaoMaster;
    }

    public DaoSession getmDaoSession() {
        return mDaoSession;
    }
}

注意上面的删除语句,使用的话:

  GreendaoUtil.getInstance().getmDaoSession().getDatabase().execSQL(GreendaoUtil.SQL_Delete + mdeleteText);

其中 SQL_Delete中SearchHistoryDao.TABLENAME就是你的表名,text其实就是你的字段
这样就能删掉该条数据。

2.非主键去重插入

        Cursor cursor = GreendaoUtil.getInstance().getmDaoSession().getDatabase().rawQuery(GreendaoUtil.SQL_DISTINCT_ENAME, null);
        mHistoryList.clear();
        try {
            if (cursor.moveToFirst()) {
                do {
                    mHistoryList.add(cursor.getString(0));
                } while (cursor.moveToNext());
            }
        } finally {
            cursor.close();
        }

利用这个去重,然后将最后的集合加入Recyclerview。