One-to-many relation in Room - android

I've been using SugarDB for most of my projects in the past. It was easy to use and satisfied most of my requirements but since that project has been abandoned, decided to look at alternatives and Room seems like the best option.
However, some basic things are quite confusing in Room. My Object uses Gson to populate data from a webservice, and as such as links to other objects. As an example, consider the classes below:
#Entity
public class TestModel
{
#PrimaryKey(autoGenerate = true)
private int id;
private String name;
private String age;
private List<Book> issuedBooks;
}
public class Book
{
private String title;
private int ISBN;
}
Now if my first class is annotated as the Entity, will this automatically treat classes referenced inside it as entities as well?
If I save an object of TestModel, will it save the list of Books with it to the database?

I guess you can do it this way.
#Entity
public class TestModel {
#PrimaryKey
public int id; // TestModel id
public String name;
public String age;
}
#Entity
public class Book {
#PrimaryKey
public int id; // Book id
public int testModelId; // TestModel id
public String title;
public int ISBN;
}
public class TestModelWithBooks {
#Embedded
public TestModel testModel;
#Relation(parentColumn = "id", entityColumn = "testModelId", entity = Book.class)
public List<Book> books;
}
For their Dao, you can write it this way.
#Dao
public interface TestModelDao {
#Query("SELECT * FROM TestModel")
public List<TestModelWithBooks> loadTestModelsWithBooks();
}

will this automatically treat classes referenced inside it as entities as well?
No. In fact, I would expect your code to fail to compile. You would need to:
Make Book be an #Entity
Remove issuedBooks from TestModel
Set up a #ForeignKey relationship between Book and TestModel
If I save an object of TestModel, will it save the list of Books with it to the database?
No.
Room is not an ORM. Room is a thin object wrapper around SQLite. #Entity and #ForeignKey model the table structure. IMHO, the simplest way to think of Room as it being DTOs to the database. Your model objects that represent your object graph are not the entities, but instead are built from the entities. This is akin to how responses from a Web service (e.g., Retrofit) are DTOs to the server, and you may need to map from those objects to the "real" model objects that you want to use in the app.

Related

Storing list of same type type as entity

Lets suppose I have an entity "Article" and it may have a list of Articles inside it received from the api. The question is how to save this list that has the same type as the entity using room.
I am saving them as embedded using type converters but nothing is saved
#Entity(tableName = "articles")
public class Article {
#Embedded
#TypeConverters(ArticleTypeConverter.class)
#SerializedName("relatedArticles")
#Expose
private ArrayList<Article> relatedArticles = null;
}
In your case, Article class should be an object that mimics the structure of the article you're getting from the server. In addition, you will need a separate class that holds a List of those Article instances.
public class Article {
//.....
private String title;
private String author;
//.....
}
and here's the class you need to save
#Entity(tableName = "articles")
public class Articles {
//.....
#SerializedName("relatedArticles")
public List<Article> relatedArticles;
//.....
}
NOTE I added the Article class w/ fields I imagined it would have, but for it to work it'd need to match names/types of fields that your server returns.

Android Room Relationships -- List of Foreign Keys

I'm having trouble understanding how to set up my Room relationships. I haven't found an example analogous to mine anywhere online.
I have a User object (I've left out getters and setters):
#Entity
public class User {
#PrimaryKey
#NonNull
private String userId;
#ColumnInfo
private String name;
#ColumnInfo
private List<Long> seminarsAttended;
}
and a Seminar object:
#Entity
public class Seminar {
#PrimaryKey
private Long seminarId;
#ColumnInfo
private String topic;
....}
The list "seminarsAttended" in the User object is a list of seminarIds. The User class is linked up to a Retrofit call, so I can't modify the class to instead hold a list of Seminar objects.
How can I model this relationship in Room, such that the seminarIds in the User's seminarsAttended list are correlated with their corresponding Seminar in the seminars.db table?
It looks like the list of seminarsAttended should be a list of foreign keys into the seminars.db table, but I'm having trouble finding an example.

How to link Room database entities on android?

I am quite familiar with these kind of thing on Spring JPA but I can not make it work on Android. I post my code below so you can understand the question better. I have two classes and a third class that needs to contain objects of class 1 and 2. I know that the code for the third class is not correct, since Room does not support object references like that. If I save just the id-s of the objects as foreign keys I am not able to query after the results.
There must be some kind of nice solution for this problem. Thank you.
#Entity(tableName = "soup")
public class Soup {
#PrimaryKey(autoGenerate = true)
private long id;
private String name;
// getter and setters
}
#Entity(tableName = "main_course")
public class MainCourse {
#PrimaryKey(autoGenerate = true)
private long id;
private String name;
// getter and setters
}
#Entity(tableName = "menu")
public class Menu {
#PrimaryKey(autoGenerate = true)
private long id;
private Soup soupOptionOne;
private Soup soupOptionTwo;
private Soup soupOptionThree;
private MainCourse courseOptionOne;
private MainCourse courseOptionTwo;
private MainCourse courseOptionThree;
}

How to handle relationships in Room?

I'm testing Room persistence library. I have two entity classes:
#Entity
public class User {
#PrimaryKey
int id;
String name;
}
#Entity(foreignKeys = #ForeignKey(entity = User.class,
parentColumns = "id",
childColumns = "userId")
public class Pet {
#PrimaryKey
int id;
String name;
int userId;
}
Now I'd like to get list of Pet and in each Pet object keep actual reference to User according to his userId. So each time when the userId is changed, this reference also should be changed. Is it possible to do? Or maybe there is a better way to handle relation like this?
Actually, ROOM not recommended to do that. The reasons are in the reference link.
Maybe you could try it,
#Entity
public class User {
#PrimaryKey
int id;
String name;
#Embedded
public List<Pet> userPet;
}
public class Pet {
int id;
String name;
}
Understand why Room doesn't allow object references
A convenience annotation which can be used in a Pojo to automatically fetch relation entities.

How to handle Object References in Entity?

I have the following structure to save to app database:
#Entity
public class Project{
#primaryKey
String id;
String name;
[...]
Country country;
[...]
}
And my Country Entity looks like the following:
#Entity
public class Country {
#PrimaryKey
private String id;
private String name;
private String pk;
}
Now to my Question: How do I make Room know the Relation between Country and Project Entity?
Room can not have nested entities, you can embedd POJO classes in an entity but it will get flattened into a single table or if you want Country as an entity then you'll have to store county_id in Project entity and index it as foreign key.
More on Embedded fields: https://developer.android.com/reference/android/arch/persistence/room/Embedded.html
More on Foreign key: https://developer.android.com/reference/android/arch/persistence/room/ForeignKey.html
Please refer the official documentation
https://developer.android.com/reference/android/arch/persistence/room/Relation.html

Categories

Resources