最近使用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; } }
方法出处session