ORMlite Android foreign key support

Waypoint picture Waypoint · Jan 25, 2012 · Viewed 20.1k times · Source

I am not clever from ORMlite documentation. Is is possible to declare in class, that this parameter is foreign key?

e.g. I have table Customer:

@DatabaseTable(tableName = "customer")
public class Customer {
    @DatabaseField(id = true)
    private String customerName;

    @DatabaseField
    private String customerSurname;

    @DatabaseField(foreign = true)
    private String accountNameHolder;

    @DatabaseField
    private int age;

    public Customer() {
    }
}

AccountNameHolder should aim towards DatabaseField name from table Accounts. How to do that? I have found only parameter foreign = true, but there is nothing about, which parameter and from which table it represents.

Thanks

Answer

Gray picture Gray · Jan 25, 2012

AccountNameHolder should aim towards DatabaseField name from table Accounts. How to do that?

I'm not exactly sure what you want but possibly you should change your foreign field to be the actual type instead of a name:

@DatabaseField(foreign = true)
private Account account;

Internally, ORMLite will store a account_id field (maybe the string name) in the Customer table but you don't have to worry about that. Remember that when you query for a Customer, the Account that is set on the account field will just have the id field set. To have ORMLite also lookup the account you will need to set the foreignAutoRefresh=true.

As @Lalit pointed out, here is some documentation on this subject. We've spent a long time on the documentation so it should be helpful.

Also, there is some example code about foreign fields.

Hope this helps.