I am using Room in my Android App (Java) and there I have two entities with a 1:many relation.
Lens entity One lens can have multiple wears.
@Entity(tableName = "lens_table")
public class Lens {
@PrimaryKey(autoGenerate = true)
private int lensId;
private String name;
}
Wear entity One wear can only relate to one lens.
@Entity(tableName = "wear_table",
foreignKeys = {@ForeignKey(
entity = Lens.class,
parentColumns = "lensId",
childColumns = "fk_lensId",
onDelete = ForeignKey.CASCADE)},
indices = {@Index("fk_lensId")})
public class Wear {
@PrimaryKey(autoGenerate = true)
private int wearId;
private String name;
private int fk_lensId;
}
So far so good. I am fine with the "standard" queries (create, get all, update, delete,...) so far, where a lot of documentation is around. I also was successful implementing the query to get all lenses with their wears based on below relation.
public class LensWithWears {
@Embedded
public Lens lens;
@Relation(
parentColumn = "lensId",
entityColumn = "fk_lensId"
)
public List<Wear> wears;
}
But now I need to query the following information:
Get a single wear with the associated lens by looking up the wearId
The relationship class I am currently using looks like following:
public class WearWithLens {
@Embedded
public Wear wear;
@Relation(
parentColumn = "wearId",
entityColumn = "lensId"
)
public Lens lens;
}
And the Dao Query looks like that:
@Query("SELECT * FROM wear_table WHERE wearId = :wearId LIMIT 1")
LiveData<WearWithLens> getWearWithLensByWearId(int wearId);
My code obviously does not work, otherwise I would not ask... The problem is, that an object WearWithLens is returned, but the lens object in it is always null.
In other words, I would like to query a Wear, which has a 1:1 relation to a lens and get both objects together in the class WearWithLens.
Can somebody tell me how the query should look like?
Thanks!