Home > Software engineering >  Is room capable of getting data from dataclasses?
Is room capable of getting data from dataclasses?

Time:08-01

this might be a basic question but I cannot find any way to do it and I am not even sure whether that it is possible: let's say I have a data class named "LoginCredentials", which takes 2 values: username and password (both strings) could I make a query that looks like that?:

@Query("SELECT * FROM X WHERE username = :loginCredentials.username AND password = :loginCredentials.password")

or is there any other way to do it?

CodePudding user response:

I don't think it's possible - I'm not a Room expert, but the documentation only mentions referencing parameters and expanding collections in a @Query string. There's nothing about using more complex, arbitary data structures.

I think the way you're meant to do it is with a public method in your DAO that takes your data structure, and have that internally call another function that takes the individual parameters:

@Dao
interface MyDao {

    @Query("SELECT * FROM X WHERE username = :username AND password = :password")
    fun getFromUserAndPass(username: String, password: String): Whatever

    fun getFromLoginCreds(creds: LoginCredentials) =
        getFromUserAndPass(creds.username, creds.password)

}

There's no way to make that "internal" version private that I know of (adding it to an interface disallows that, not sure if there's an alternative) but you can always abstract access to your DAO through a repository layer or something, with its own API

  • Related