How to build query with selecting by value of foreign object's field
Asked Answered
B

1

5

What is the best way for querying by using the value of foreign object's field?

Suppose I have these three classes.

UnitResult class which describes amount of Units:

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

Unit class which describes certain Units in a market (for example jiuce, snack etc.):

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

And Enum of Unit type:

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

So how can I query all UnitResult where Unit type is UnitType.JUICES?

Berniecebernier answered 20/6, 2012 at 11:17 Comment(0)
T
16

So how can I query all UnitResult where Unit type is UnitType.JUICES?

The way to do this in ORMLite is to use the `Where.in(...) with a sub-query:

// 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();
Tinned answered 20/6, 2012 at 17:9 Comment(3)
Thank you very much, Gray! And respect for OrmLite library! :)Berniecebernier
This no longer seems to work. Because the id column is automagically added to the query, it throws "SQLException, Inner query must have only 1 select column specified instead of *".Bullyrag
Followup: I believe the intent is that you now use a join.Bullyrag

© 2022 - 2024 — McMap. All rights reserved.