如何在 OrmLite 中获取 column/field 个名字?

How to get column/field names in OrmLite?

我正在通过常用注释定义 table/field 名称,例如:

@DatabaseTable(tableName = "M")
public class Headers {
    //android requires primary key as _ID
    @DatabaseField(generatedId = true, columnName = "_ID", dataType = DataType.INTEGER_OBJ)
    private Integer id;

    @DatabaseField(
            columnName = "MM2",
            uniqueCombo = true,
            canBeNull = true, //null means root folder
            dataType = DataType.INTEGER_OBJ
    )
    private Integer parentId;
}

与此同时,在我的代码深处的某个地方,我需要进行一些查询,例如:

QueryBuilder<Headers, Integer> qb = headersDao.queryBuilder();
qb.where().eq("_ID",  headerId); //_ID field name

这种代码看起来很难看,因为字段名称(在本例中为 _ID)是硬编码的(即使声明为 final static String

问题:OrmLite编码习惯正常吗?我希望我可以使用一些小代码来代替硬编码 _ID 字段。确保 OrmLite "knows" 所有字段名称。谁能帮帮我?

为字段名定义一个常量,如

private static final String FIELD_ID = "_ID";
// Or make it public as Gray said into comment
public static final String FIELD_ID = "_ID";

并像

一样使用它
//android requires primary key as _ID
@DatabaseField(generatedId = true, columnName = FIELD_ID, dataType = DataType.INTEGER_OBJ)
private Integer id;

并进入您的查询

QueryBuilder<Headers, Integer> qb = headersDao.queryBuilder();
qb.where().eq(FIELD_ID,  headerId); //_ID field name

如果你看 documentation

他们也遵循相同的

QueryBuilder<Account, String> qb = accountDao.queryBuilder();
Where where = qb.where();
// the name field must be equal to "foo"
where.eq(Account.NAME_FIELD_NAME, "foo");
// and
where.and();
// the password field must be equal to "_secret"
where.eq(Account.PASSWORD_FIELD_NAME, "_secret");
PreparedQuery<Account, String> preparedQuery = qb.prepareQuery();