I\'m new to Android Room. I want to read from a table and also read from a related table. The relationship is pretty common. One table defines instances. The other table defines
waqaslam pointed the way to the solution. He suggested to alias the column names. The additional step is to give the second table a prefix.
public class AnimalWithType {
@Embedded
private Animal animal;
@Embedded(prefix = "type_")
private AnimalType type;
...
The column aliases are long and messy. I hope that someone can find a cleaner way.
@Query("select animal.id, animal.name..., animal_type.id as type_id... from animal join animal_type on (animal.id = animal_type.id)")
Instead of using *
to collect all the fields, you need to specifically provide column names because id is found in both tables hence causing the error. Change your query to something like:
select animal.id AS 'ID', animal.columnA, animal.columnB,
animal_type.columnA, animal_type.columnB from animal
join animal_type on (animal.id = animal_type.id)
You dont need to fetch IDs from both tables since they will be same, so one is enough. However, replace coulmnA, columnB, etc. with the valid column names you want to fetch.
I solved that problem by adding prefix to column names so they are unique. If your case does not allow changing column names you should use some of the provided answers and @Embedded(prefix) annotation.
@Entity(tableName = "animal")
public class Animal {
@PrimaryKey
@ColumnInfo(name = "animal_id")
public long id;
...
}
@Entity(tableName = "animal_type")
public class AnimalType {
@PrimaryKey
@ColumnInfo(name = "animal_type_id")
public long id;
...
}
And your query will be:
SELECT * FROM animal JOIN animal_type ON animal_id = animal_type_id