0

I have these classes:

@Entity
public class Person {
    long id;
    String name;
}


@Entity
public class Dog {
    long id;
    String color;

    long idPerson;
}


public class PersonWithDog {
    @Embedded
    Person person;

    @Relation(parentColumn = "id", entityColumn = "idPerson", entity =     Dog.class)
    List<Dog> dogs;
}

I want to make a query to return a person and a list of only black dogs he owns. Something like:

SELECT * FROM Person 
LEFT JOIN Dogs ON Person.id = Dogs.idPerson 
WHERE Person.id = ? AND Dogs.color = black

Is this possible using Room?

**Note: If I make a POJO this way:

public class PersonWithDog {
    @Embedded
    Person person;

    @Embedded
    List<Dog> dogs;
}

and use the above query, Room won't find out how to map the fields of List, as it doesn't accept an embedded list...

  • Take a look at [this question](https://stackoverflow.com/questions/49005681/room-relations-with-conditions). – Mahozad May 08 '19 at 16:59
  • The answer to this question doesn't seems to work... I can't @Embedded a List. If I do this with an join query, I get the error "The query returns some columns [...] which are not use by ..." – Артур Олмос May 09 '19 at 12:12

1 Answers1

0

If nothing else worked, this dirty solution may help you as a last resort. Note that the return type could not be LiveData and you should call the method every time you need the data (and perhaps wrap its result in a SingleLiveEvent or something):

@Dao
public abstract class MyDao {

    // Call this method
    @Transaction
    Map<Person, List<Dog>> getPersonBlackDogs(long personId) {
        Person person = getPerson(personId);
        List<Dog> blackDogs = getBlackDogs(personId);
        return Collections.singletonMap(person, blackDogs);
    }

    // You do not want to expose these two methods so make theme protected

    @Query("SELECT * FROM Person WHERE id = :personId")
    protected abstract Person getPerson(long personId);

    @Query("SELECT * FROM Dog WHERE idPerson = :personId AND Dog.color = black")
    protected abstract List<Dog> getBlackDogs(long personId);
}
Mahozad
  • 18,032
  • 13
  • 118
  • 133