One-to-many with lightweight many

Viewed 40

Room lets you query for specific columns using a POJO with just those columns. (Incidentally, is @ColumnInfo necessary if the property name matches the column name?)

Documentation example:

data class NameTuple(
    @ColumnInfo(name = "first_name") val firstName: String?,
    @ColumnInfo(name = "last_name") val lastName: String?
)

// In DAO:
@Query("SELECT first_name, last_name FROM user")
fun loadFullName(): List<NameTuple>

When doing a one-to-many query, is there a way to select just a subset of columns from the dependent entity? All of the examples of relationships in the documentation show POJOs that combine the Entity classes into a POJO linking Entity classes, but not one of the non-entity tuples like above.

How do you tell it which columns to select in the implicit second query of the @Transaction?

I don't even know where to begin setting it up, or what the query code would be. For the sake of example, suppose you have a Person table and Pet table, and you want to be able to get a flow of all Persons with their pet's names, but none of the other pet data.

@Entity
data class Person(
    @PrimaryKey(autoGenerate = true) val id: Int = 0,
    val name: String = ""
)

@Entity
data class Pet(
    @PrimaryKey(autoGenerate = true) val id: Int = 0,
    val ownerId: Int = 0,
    val name: String = "",
    val animalType: String = "",
    val birthdate: Long = 0
)

// ...

data class PetName (
    @ColumnInfo(name = "id") val id: Int = 0,
    @ColumnInfo(name = "name") val name: String = ""
)

PersonWithPetsNames {
    @Embedded val person: Person,
    @Relation(parentColumn = "id", entityColumn = "ownerId", entity = Pet::class)
    val pets: List<PetName>
}

// in DAO:
@Transaction
@Query("SELECT * FROM Person ...???")
fun getPeopleWithPetNames(): Flow<List<PersonWithPetsNames>>
1 Answers

In JPA, you can select any columns for constructing entities. In general, you can use EntityGraph to control the graph of entities(and attributes) to be fetched. JPA is java standard, and you can reuse code on android, java server side or swing project. see Cmobilecom-JPA for android.

Related