ORMLite - Query foreign field

2019-04-25 11:06发布

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?

2条回答
The star\"
2楼-- · 2019-04-25 11:50

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();
查看更多
▲ chillily
3楼-- · 2019-04-25 11:58

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

查看更多
登录 后发表回答