利用ORMLite将Android游标映射到POJO?

时间:2013-12-24 01:22:51

标签: android cursor android-contentprovider ormlite

由于ORMLite已经将Android游标映射到POJO。 我想知道我是否能以某种方式利用它而不是编写复制构造函数并手动将Cursor映射到我的POJO?

例如,我可以使用内容提供程序并将结果映射到由ORMLite的Dao支持的相同POJO中。 对我的数据集执行操作,然后使用ORMLite将该数据批量插入到我的数据库中。 这样做的好处是我不必编写所有CRUD ofc。

修改

这是一个捏造的例子,但概念就在这里。做这样的事情最好的方法是什么?

@DatabaseTable(tableName = "my_dict")
public class MyDictionary{
    @DatabaseField(columnName = COLUMN_ID, generatedId = true)
    Integer _ID;
    @DatabaseField(columnName = "word")
    String word;
    @DatabaseField(columnName = "app_id")
    String app_id;
    @DatabaseField(columnName = "frequency")
    Integer frequency;
    @DatabaseField(columnName = "locale")
    String locale;

    public MyDictionary(){}     
}

public void someCoolDatasetOperation(){

    Dao<MyDictionary, Long> dao = databaseHelper.getDao(MyDictionary.class);

    List<MyDictionary> inDb = dao.queryForAll();

    Cursor dictCursor = getContentResolver().query(WEB_SERVICE_URI,
            null,                        // The columns to return for each row
            null,                    // Selection criteria
            null,                     // Selection criteria
            null);                        // The sort order for the returned rows


    //iffy part don't know the correct/best way to do this?????
    AndroidDatabaseResults fabricatedResult = new AndroidDatabaseResults(dictCursor, null);     
    List<MyDictionary> fromContentProvider = dao.mapSelectStarRow(dictCursor);

    //Do Something with the lists
}

1 个答案:

答案 0 :(得分:0)

我对ORMLite知之甚少,我并不认为两者会相处,但我正在研究可以使用带注释类生成游标的POJO包装的库。 / p>

因此,如果我尝试在上面的示例中使用此库,它可能如下所示:

@Entity
public class MyDictionary{
    @Attribute(sqliteName = COLUMN_ID, primaryKey = true, autoIncrement = true)
    Integer _ID;
    @Attribute(sqliteName = "word")
    String word;
    @Attribute(sqliteName = "app_id")
    String app_id;
    @Attribute(sqliteName = "frequency")
    Integer frequency;
    @Attribute(sqliteName = "locale")
    String locale;
}

public void someCoolDatasetOperation(){

    Dao<MyDictionary, Long> dao = databaseHelper.getDao(MyDictionary.class);

    List<MyDictionary> inDb = dao.queryForAll();

    Cursor dictCursor = getContentResolver().query(WEB_SERVICE_URI,
            null,                    // The columns to return for each row
            null,                    // Selection criteria
            null,                    // Selection criteria
            null);                   // The sort order for the returned rows

    List<MyDictionary> fromContentProvider = new ArrayList<MyDictionary();

    while(dictCursor.moveToNext()) {
        //MyDictionaryEntity is a generated class that contains getters and 
        //setters for all the attributes in MyDictionary
        fromContentProvider.add(new MyDictionaryEntity(dictCursor));
    }
}

我还在积极开发它并且还没有太多的文档,但如果你想查看它: https://github.com/adecker89/Glowplug