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;
@DatabaseField
private String name;
// default constructor, getters and setters...
}
The raw SQL I'm looking for would be something like this:
SELECT
o.*
FROM
order o
JOIN customer c on
o.customer_id = c.id
WHERE
(o.id = ?) OR (c.name = ?)
What is the best way to do this using ORMLite?
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);
orderQb.join(customerQb);
// then you set the args and run the query
nameSelectArg.setValue("jim");
idSelectArg.setValue(1);
List<Order> results = orderQb.join(customerQb).query();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With