ORMLite Select Distinct Fields

旧城冷巷雨未停 提交于 2019-12-19 07:54:36

问题


I have a SQLite table (on Android) that has numerous fields, but certain fields are repeated/denormalized. I would like to select a distinct set of this data and use them as actual objects.

Example

books table

title            summary        author
Little Johnny    A funny kid    Johnny Himself
Big Johnny       A funny adult  Johnny Himself

I would like to extract one author from this list ("Johnny Himself") and would expect I should be able to do this with ORMLite instead of manually with Java.


回答1:


I would like to select a distinct set of this data and use them as actual objects.

ORMLite supports a distinct() method on the QueryBuilder that should do what you want. So your code would look something like:

List<Book> results = booksDao.queryBuilder()
    .distinct().selectColumns("author").query();

In this case, the resulting Book objects would only have the author field set and not the id field or anything else. If you just wanted the author names instead of objects then you could do:

GenericRawResults<String[]> rawResults =
    booksDao.queryRaw("SELECT DISTINCT author FROM books");
for (String[] resultColumns : rawResults) {
    String author = resultColumns[0];
    ...
}



回答2:


This is my application code

public class DbHelper<T> {
    private Class<T> c;
    private DatabaseHelper db;
    public DbHelper(Class<T> c) {
        this.c = c;
        db = DatabaseHelper.getInstance();
    }

This is a good idea

public List<T> queryForBuilderDistinct(int offset, int limit, String ColumnsName,
       String orderName, boolean isAsc) {
    try {
        Dao<T, Integer> dao = db.getDao(c);
        QueryBuilder<T, Integer> queryBuilder = dao.queryBuilder();
        if (offset != 0) {
            queryBuilder.offset((long) offset);
        }
        if (limit != 0) {
            queryBuilder.limit((long) limit);
        }
        if (orderName != null) {
            queryBuilder.orderBy(orderName, isAsc);
        }
        queryBuilder.distinct().selectColumns(ColumnsName);
        return dao.query(queryBuilder.prepare());
    } catch (SQLException e) {
        LogUtil.e(TAG, "queryForBuilderDistinct", e);
    }
    return new ArrayList<T>();
}


来源:https://stackoverflow.com/questions/12190786/ormlite-select-distinct-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!