Search code examples
androidandroid-sqliteandroid-roomandroid-database

Room: Relation entities using Room,(One to many) Retrieve one with condition rather than all elements


My Question is similar with Android Room: Insert relation entities using Room but with little changes

@Entity
public class Pet {
    @PrimaryKey
    public int id;     // Pet id
    public int userId; // User id
    public String name;
    //Added EXTRA column

    public long time;// pet since have
}

Currently UserWithPets POJO is

// Note: No annotation required at this class definition.
public class UserWithPets {
   @Embedded
   public User user;

   @Relation(parentColumn = "id", entityColumn = "userId", entity = Pet.class)
   public List<Pet> pets;
}

And Query is

    @Query("SELECT * FROM User")
    public List<UserWithPets> loadUsersWithPets();

But I need something like that UserWithLatestPet POJO:

public class UserWithLatestPet {
   @Embedded
   public User user;

   @Relation(parentColumn = "id", entityColumn = "userId", entity = Pet.class)
   public Pet latestPet;//Retrieve only latest (since time) pet per user
}

//Query
@Query("SELECT * FROM User")
public List<UserWithLatestPet> loadUserWithLatestPet();

What will be best way to query with only latest pet from Pet Entity along with User


Solution

  • First, you can define a single Pet as the result of the Relation only since Room Version 2.2.0-alpha01

    I think you can do 2 things: 1. Create a query to left join the needed pet 2. Create a correct relation List<Pet> and then scan the List of the latest one.

    In case you want to save a little you can create a POJO that holds only the time and id of the List of pets so you only get the minimal data you need, scan the List for the latest one and then query for that Pet.