5

使用外来对象字段的值进行查询的最佳方法是什么?

假设我有这三个类。

描述单位数量的 UnitResult 类:

@DatabaseTable
public class UnitResult {
    public static final String ID_FIELD_NAME = "id";
    public static final String UNIT_COLUMN_NAME = "unit";
    public static final String RESULT_COLUMN_NAME = "result";

    @DatabaseField(generatedId = true, columnName = ID_FIELD_NAME)
    public Integer id;

    @DatabaseField(foreign = true, canBeNull = false, columnName = UNIT_COLUMN_NAME)
    public Unit unit;

    @DatabaseField(canBeNull = true, columnName = RESULT_COLUMN_NAME)
    public Integer result = null;
}

描述市场中某些单位的单位类别(例如果汁、零食等):

@DatabaseTable
public class Unit {
    public static final String ID_FIELD_NAME = "id";
    public static final String TYPE_FIELD_NAME = "type";

    @DatabaseField(id = true, columnName = ID_FIELD_NAME)
    public int id;

    @DatabaseField(canBeNull = false, columnName = TYPE_FIELD_NAME)
    public UnitType type;
}

以及 Unit 类型的枚举:

public enum UnitType {
    JUICES,
    DRINKS,
    SNACKS,
    NPD;
}

那么如何查询所有类型在UnitResult哪里?UnitUnitType.JUICES

4

1 回答 1

16

那么如何查询 Unit 类型为 UnitType.JUICES 的所有 UnitResult?

ORMLite中执行此操作的方法是将`Where.in(...) 与子查询一起使用

// setup our sub-query on the Unit table first
QueryBuilder<Unit,Integer> uQb = unitDao.queryBuilder();
uQb.where().eq(Unit.TYPE_FIELD_NAME, UnitType.JUICES);
// outer query on UnitResult table
QueryBuilder<UnitResult,Integer> urQb = unitResultDao.queryBuilder();
// in using the sub-query
urQb.where().in(UnitResult.UNIT_COLUMN_NAME, uQb);
List<UnitResult> results = urQb.query();
于 2012-06-20T17:09:07.757 回答