I am currently playing with Room in order to compare it with Realm and I already have so many question about the best way to do things.
In my sample app, I have a really simple model in which one a Person
can have Cat
s and Dog
s.
Here the java classes.
Cat
and Dog
classes inherit from an Animal
class :
public abstract class RoomAnimal
{
@PrimaryKey
public int id;
public int age;
public String name;
}
The Cat
class :
@Entity(tableName = "cat")
public final class RoomCat
extends RoomAnimal
{
}
The Dog
class :
@Entity(tableName = "dog")
public final class RoomDog
extends RoomAnimal
{
public enum RoomColor
{
Black, White
}
public static final class RoomColorConverter
{
@TypeConverter
public RoomColor fromString(String color)
{
return color != null ? RoomColor.valueOf(color) : null;
}
@TypeConverter
public String fromRealmColor(RoomColor color)
{
return color.toString();
}
}
@TypeConverters(RoomColorConverter.class)
public RoomColor color;
}
The Person
class :
@Entity(tableName = "person")
public final class RoomPerson
{
@PrimaryKey
public int id;
public String name;
}
I also have a POJO in order to modelize the fact that a user can have cats and dogs :
public final class RoomPersonWithAnimals
{
@Embedded
public RoomPerson person;
@Relation(parentColumn = "id", entityColumn = "id", entity = RoomDog.class)
public List<RoomDog> dogs;
@Relation(parentColumn = "id", entityColumn = "id", entity = RoomCat.class)
public List<RoomCat> cats;
}
The question is : how to save a list of RoomPersonWithAnimals
objects ?
I cannot use the Insert
annotation in a Dao
class because the RoomPersonWithAnimals
is not an Entity
.
For each objects of my list of RoomPersonWithAnimals
should I run 3 requests ?
person
attribute ;cats
;dogs
;Thank you in advance for your help !
how to save a list of RoomPersonWithAnimals objects ?
You don't, at least in the 1.0.0-alpha6
version of Room, as those are not entities.
For each objects of my list of RoomPersonWithAnimals should I play 3 requests ?
Yes. You can use runInTransaction()
to perform those three operations inside a single SQLite transaction.