我通过常规注释定义表/字段名称,例如:
@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&#34;肯定知道&#34;所有字段名称。有人可以帮帮我吗?
答案 0 :(得分:3)
为字段名称定义常量,例如
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();