How do I get the column / field names in OrmLite?
I define table and field names through regular annotations, for example:
@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;
}
Meanwhile, somewhere deep in my code, I need to make multiple requests, like:
QueryBuilder<Headers, Integer> qb = headersDao.queryBuilder();
qb.where().eq("_ID", headerId); //_ID field name
This kind of code looks ugly as the field name (in this case _ID
) is hardcoded (even if it is declared as final static String
)
Question: Is this a common practice for coding OrmLite? I was expecting that _ID
I could use a little code instead of a hardcoded field . Surely OrmLite "knows" all the field names. Can anyone help me?
+3
source to share
1 answer
Define a constant for the field name like
private static final String FIELD_ID = "_ID";
// Or make it public as Gray said into comment
public static final String FIELD_ID = "_ID";
and use it like
//android requires primary key as _ID
@DatabaseField(generatedId = true, columnName = FIELD_ID, dataType = DataType.INTEGER_OBJ)
private Integer id;
And in your request
QueryBuilder<Headers, Integer> qb = headersDao.queryBuilder();
qb.where().eq(FIELD_ID, headerId); //_ID field name
If you look at the documentation
They also follow the same
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();
+3
source to share