Search code examples
androidandroid-roomandroid-romroom

Is a good practice to extend a Room Entity and use the same DAO and Repository?


I wanna create two entities with the same fields and I saw that I can extend a entity to inherits fields, I'd like to know if it's a good practice to do it and if is there any problem to use one single DAO and Repository to these entities.

Entity that I want to reuse

@Entity
public class LoggedUsers {
    @PrimaryKey
    public int id;
    public String firstName;
    public String lastName;
}

New entity with same fields

@Entity
public class HistoryUsers extends LoggedUsers  {

        //Same fields of the other entity

}

Solution

  • As @MergimRama said, it's not a good idea. Use embedded objects.

    With embedded objects, I should create a class with fields that I want to use:

    public class UserName {
    
        public String firstName;
        public String lastName;
    
    }
    

    And reuse the class with the fields in my entities, like that :

    @Entity
    public class LoggedUsers {
    
        @PrimaryKey public int id;
    
        @Embedded public UserName username;    //Here goes the fields
    
    }
    
    @Entity
    public class HistoryUsers {
    
        @PrimaryKey public int id;
    
        @Embedded public UserName username;    //Here goes the fields
    
    }