Question

I've never used OrmLite before but I need to edit an existing project that uses it.

I have two classes : Person and Office.

I'm using gson to parse, with the person an office Id is provided, for example office_id: "4456".

I was hoping it would be possible to link the two together from my Person class so I can easily get a office for a person.

For example:

@SerializedName("id")
@DatabaseField(id = true, columnName = ID)
private int mId;

@SerializedName("full_name")
@DatabaseField(columnName = FULL_NAME)
private String mFullName = null;

@DatabaseField(columnName = POSITION)
private String mPosition = null;

@SerializedName("email")
@DatabaseField(columnName = EMAIL)
private String mEmail = null;

private Office office = null;

@SerializedName("office_id")
private String officeId = null;

So I have the officeId from Json which is stored in the Person table. I would like to automatically load the Office into the Person object whenever it is loaded.

Was it helpful?

Solution

To automatically fetch a referenced object upon querying you can use foreignAutoRefresh = true in your @DatabaseField. You reference the Object and not the id itself. In the table, the id of the referenced row will be stored.

To clarify for your project: Office must look something like this:

@SerializedName("id")
@DatabaseField(id = true, columnName = ID)
private int mId;

...

And your Person (database-wise) like this:

@DatabaseField(id = true, columnName = ID)
private int mId;

@DatabaseField(columnName = FULL_NAME)
private String mFullName = null;

@DatabaseField(columnName = POSITION)
private String mPosition = null;

@DatabaseField(columnName = EMAIL)
private String mEmail = null;

@DatabaseField(foreign = true, foreignAutoRefresh = true)
private Office office = null;

The Office column in the Person table will hold the id of the Office.

foreignAutoRefresh tells ORMLite to fetch the full Office upon querying the Person http://ormlite.com/javadoc/ormlite-core/com/j256/ormlite/field/DatabaseField.html#foreignAutoRefresh()

Hope this helps

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top