0

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

}
  • For this case, it is not a good idea. You should make a relationship between them instead. – Mergim Rama Oct 14 '20 at 21:58
  • I'm a begginer with that, could you tell me how to do it or somewhere to check ? – Breno César Oct 14 '20 at 22:05
  • You can find a good example here: https://developer.android.com/training/data-storage/room/relationships – Mergim Rama Oct 14 '20 at 23:17
  • Thank you Dude! So.... just to clarify, let's say if I create a class called ' UserName ' with the field names declared and inside the entity I put ' @Embedded public UserName userName; ', I'll have both entities with the same field names, right ? – Breno César Oct 15 '20 at 02:11
  • Yes, it adds those columns to the entity you're embedding. – Mergim Rama Oct 15 '20 at 08:27

1 Answers1

1

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

}