Barmaley
Barmaley

Reputation: 16363

How to get column/field names in OrmLite?

I'm defining table/field names thru usual annotations, like:

@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;
}

Meantime somewhere deep in my code, I need to make some queries, like:

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

This kind of code looks ugly, since field name (in this case _ID) is hardcoded (even if would be declared as final static String)

Question: is it normal OrmLite coding practice? I'd be expecting that I could use instead of hardcoded _ID field some small code. For sure OrmLite "knows" all field names. Anyone can help me?

Upvotes: 3

Views: 2380

Answers (1)

Pankaj Kumar
Pankaj Kumar

Reputation: 82958

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 as like

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

And into your query

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

If you look at 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();

Upvotes: 3

Related Questions