Home » Android » android – ORMLite – Query foreign field

android – ORMLite – Query foreign field

Posted by: admin June 15, 2020 Leave a comment


Using ORMLite for Android, I need to build a query that returns orders by order id or by customer name. Please consider the following class declarations:

@DatabaseTable(tableName = "order")
public class Order {
    @DatabaseField(generatedId = true)
    private Long id;

    @DatabaseField(foreign = true, canBeNull = false, foreignAutoRefresh = true, columnName = "customer_id")
    private Customer customer;

    // default constructor, getters and setters...

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

    private String name;

    // default constructor, getters and setters...

The raw SQL I’m looking for would be something like this:

    order o
    JOIN customer c on
        o.customer_id = c.id
    (o.id = ?) OR (c.name = ?)

What is the best way to do this using ORMLite?

How to&Answers:

ORMLite now supports simple join queries.

So your query would look something like:

QueryBuilder<Customer, Integer> customerQb = customerDao.queryBuilder();
SelectArg nameSelectArg = new SelectArg();
// this gives the c.name = ?
customerQb.where().eq("name", nameSelectArg);
QueryBuilder<Account, Integer> orderQb = orderDao.queryBuilder();
SelectArg idSelectArg = new SelectArg();
// this gives the o.id = ?
orderQb.where().eq("id", idSelectArg);
// then you set the args and run the query
List<Order> results = orderQb.join(customerQb).query();


No, JOINs are supported in ORMLite https://stackoverflow.com/a/7320091/323128
However, this reference will give a vision how to complete your task