ORMLite - 查询洋场(ORMLite - Query foreign field)

2019-09-20 06:50发布

使用ORMLite为Android,我需要建立一个由订单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的最佳方式?

Answer 1:

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();


Answer 2:

不,连接在ORMLite支持https://stackoverflow.com/a/7320091/323128然而, 这个参考会给视力如何完成任务



文章来源: ORMLite - Query foreign field