最近使用greendao的過程中,有一個需求:將數據庫的內容根據組別展示。意思就是需要將數據庫中的所有組別取出來,然后根據組別加載數據。之前我的笨辦法是獲取所有的數據,然后對得到的數據手動去重(比較每個實體的組別值是否一致,不是就加到一個List集合中)。
笨辦法在數量比較小的數據庫里面不會有什么影響,但是為了追求完美,我查詢了數據庫,得到需要”SELECT DISTINCT”字段才能查詢,但是SQLite都不會的我,怎么會查詢這個呢?這個時候離成功很近了,不過我還是偷懶了——直接去查詢人家是怎么實現的?
private static final String SQL_DISTINCT_ENAME = "SELECT DISTINCT "+EmpDao.Properties.EName.columnName+" FROM "+EmpDao.TABLENAME; public static List<String> listEName(DaoSession session) { ArrayList<String> result = new ArrayList<String>(); Cursor c = session.getDatabase().rawQuery(SQL_DISTINCT_ENAME, null); try{ if (c.moveToFirst()) { do { result.add(c.getString(0)); } while (c.moveToNext()); } } finally { c.close(); } return result; }
通過這個方法直接就可以實現了,但是這個DaoSession對象不好找,是greendao自動生成的對象,然后在EmpDao里面增加getDaoSession()方法是無效的,一編譯就將手動添加的方法刪除了。我是在自己的GreenDaoHelper方法里面找到的,代碼如下:
/** * GreenDao多個數據庫的支持類 * Created by Administrator on 2017/4/4 0004. */ public class GreenDaoHelper { private HashMap<String,DaoSession> hash = new HashMap<String,DaoSession>(); public String pBaseDbPath = "/PuCha2.0/PestGeneralSurvey/PuChaSurvey.db"; private Context pContext; public GreenDaoHelper(Context pContex,String pBaseDbPath){ this.pContext = pContex; this.pBaseDbPath = pBaseDbPath; initDatabase(pBaseDbPath); } /** * 初始化greenDao,這個操作建議在Application初始化的時候添加; */ public DaoSession initDatabase(String pPath) { // 通過 DaoMaster 的內部類 DevOpenHelper,你可以得到一個便利的 SQLiteOpenHelper 對象。 // 可能你已經注意到了,你並不需要去編寫「CREATE TABLE」這樣的 SQL 語句,因為 greenDAO 已經幫你做了。 // 注意:默認的 DaoMaster.DevOpenHelper 會在數據庫升級時,刪除所有的表,意味着這將導致數據的丟失。 // 所以,在正式的項目中,你還應該做一層封裝,來實現數據庫的安全升級。 DaoMaster.DevOpenHelper mHelper = new DaoMaster.DevOpenHelper(pContext, FormUtil.getInnerSDCardPath()+pPath, null); SQLiteDatabase db = mHelper.getWritableDatabase(); // 注意:該數據庫連接屬於 DaoMaster,所以多個 Session 指的是相同的數據庫連接。 DaoMaster mDaoMaster = new DaoMaster(db); DaoSession mDaoSession = mDaoMaster.newSession(); hash.put(pPath,mDaoSession); return mDaoSession; } public DaoSession getDaoSession(String pDbPath) throws FileNotFoundException { DaoSession mDaoSession = hash.get(pDbPath); if(!fileIsExists(FormUtil.getInnerSDCardPath()+pDbPath)){ throw new FileNotFoundException(); } if(mDaoSession == null){ return initDatabase(pDbPath); } return mDaoSession; } public DaoSession getBaseDaoSession(){ DaoSession mDaoSession = hash.get(pBaseDbPath); if(mDaoSession == null){ return initDatabase(pBaseDbPath); } return mDaoSession; } public boolean fileIsExists(String pPath){ try{ File f=new File(pPath); if(!f.exists()){ return false; } }catch (Exception e) { // TODO: handle exception return false; } return true; } }