Room with Subclass

Viewed 2727

I'm looking to persist some data classes. I've been investigating using Room for this, which is very straight forward to do if it's just a case of a stand alone data class. However the objects I am trying to persist are sub classes, which adds a layer of complexity.

THIS CODE HAS NOT BEEN COMPILED, WRITTEN IN SO FOR ILLUSTRATION PURPOSES ONLY

So with a simple straight forward class

    @Entity(tableName = TABLE_NAME)
   public class Event implements MyEvent {
   public static final String TABLE_NAME = "events";
   public static final String DATE_FIELD = "date";

   @PrimaryKey(autoGenerate = true)
   private int id;
   private String name;
   private String description;
   @ColumnInfo(name = DATE_FIELD)
   private LocalDateTime date;

   public Event(int id, String name, String description, LocalDateTime date) {
       this.id = id;
       this.name = name;
       this.description = description;
       this.date = date;
   }

   @Override
   public int getId() {
       return id;
   }

   @Override
   public String getName() {
       return name;
   }

   @Override
   public String getDescription() {
       return description;
   }

   @Override
   public LocalDateTime getDate() {
       return date;
   }

   @Override
   public String toString() {
       return "Event{" +
               "id=" + id +
               ", name='" + name + '\'' +
               ", description='" + description + '\'' +
               ", date=" + date +
               '}';
   }

   public long getDaysUntil() {
       return ChronoUnit.DAYS.between(LocalDateTime.now(), getDate());
   }
}

That's straight forward but if you have for example

  public class MusicEvent extends Event implements MyEvents {

  private String musicType;
  private boolean supportActs;

   @Override
   public int getId() {
      return id;
   }

   @Override
   public String getName() {
       return name;
   }

   @Override
   public String getDescription() {
       return description;
   }

   @Override
   public LocalDateTime getDate() {
       return date;
   }

  public void setMusicType(String musicType) {
      this.musicType = musicType;
  }

  public String getMusicType() {
      return this.musicType;
  }

  public void setSupportActs(boolean supportActs) {
      this.supportActs = supportActs;
  }

    public boolean getSupportActs() {
      return this.supportActs;
  }
  }

  public interface MyEvents {
     int getId();
     String getName();
     String getDescription();
     LocalDate getDate();
  }

So what I want to do is have one table of events, I don't want to have multiple tables for e.g. music events, film events, drama events.

Or if they all implement MyEvents they can all be type MyEvents.

I would like to be able to persist all Event objects and when required retrieve all event objects.

If anyone could share some info on this I'd greatly appreciate it.

0 Answers
Related