Android Room: Include Nested Object's Fields as Columns

Viewed 5343

Let's say I have a Patient entity, storing the patient ID, a boolean and finally a Person object. So I annotate these fields with @ColumnInfo to store in the database.

Now a Person has 2 String fields: a first name and last name.

However, in my patients table, I want to have a column directly for the first name and last name fields (from Person), and so I want to be able to call e.g. firstName (and not having to call Person.firstName) from a query. How may I achieve this?

1 Answers

You can use @Embedded annotation of Room for it.

In your case it will be as follows

   public class Person {
       String firstName;
       String lastName;
   }

   public class Patient {
       int patientId;//just an assumption
       @Embedded
       Person person;
   } 

For more information check this Note : I haven't provided other annotations like @ColumnInfo for brevity

Related