ORMLite - Query foreign field

巧了我就是萌 提交于 2020-01-01 09:13:14

问题


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?


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/11671791/ormlite-query-foreign-field

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!