8

使用适用于 Android 的 ORMLite,我需要构建一个按订单 ID 或客户名称返回订单的查询。请考虑以下类声明:

@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...
}

我正在寻找的原始 SQL 是这样的:

SELECT 
    o.* 
FROM
    order o
    JOIN customer c on
        o.customer_id = c.id
WHERE
    (o.id = ?) OR (c.name = ?)

使用 ORMLite 的最佳方法是什么?

4

2 回答 2

13

ORMLite现在支持简单的连接查询

所以你的查询看起来像:

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();
于 2012-09-27T20:36:45.593 回答
0

不,ORMLite 支持 JOIN https://stackoverflow.com/a/7320091/323128 但是,此参考将提供如何完成任务的愿景

于 2012-07-26T15:41:49.933 回答