0

I'm wondering how to inhire to a data class in Room database. As example a have something like this

@Entity(tablename = "user")
abstract class User {
       var name: String,
       var id: Int
}

Now I want to create a specific user, that has all the attributes of the User class as an entity to store and load them from database

@Entity(tablename = "user")
data class FreeUser {
     override var name: String,
     override var id: Int,
     var freeUserAttirbute: String
} : User ()

and

@Entity(tablename = "user")
data class PremiumUser {
     override var name: String,
     override var id: Int,
     var premiumUserAttirbute: String
} : User ()

as a DAO I would write something like this

interface UserDao {
   @Query("SELECT * FROM 'user'")
   fun getAllUser(): List<User>

Now when I build my application room is telling me, that the User class can't be abstract. How can I solve this inheritance issue in data class and Room?

dudi
  • 5,523
  • 4
  • 28
  • 57

1 Answers1

0

You can try this way

open class User {
       open var name: String = ""
       open var id: Int = 0
}

data class PremiumUser(
    override var name: String,
    override var id: Int,
     var premiumUserAttirbute: String
) : User()

data class FreeUser(
     override var name: String,
     override var id: Int,
     var freeUserAttirbute: String
) : User ()

  • You can't have every entity with same table name.
  • If you retrieve User object from database you won't have additional fields from Premium or Free user.
  • If this is your reals use case than you should be fine with one entity that has name, id and flag that is boolean and if true than it is premium if is false than is free user.

There is not really much sense in using inheritence with data classes because it cancels out their purpose.

Edit answer to question in comments

Create one entity

@Entity(tablename = "users")
data class User(
    var id: Int,
    var name: String,
    var isPremium: Boolean
)

and DAO should look like this

interface UserDao {
   @Query("SELECT * FROM users")
   fun getAllUsers(): List<User>
}

This whay you get all users. If you want to see who is premium then just check if field isPremium is true. If user is free user, then isPremium should be false.

Milan Kundacina
  • 309
  • 1
  • 8
  • Thank you very much for your answer. I will try this out. My use case is, that I want get all user from the database. Premium and FreeUser. How can I do that? – dudi Oct 29 '19 at 20:44