1

Based on my research we have two way for getting related data from two or more tables.

For example if we have 2 tables like below:

@Entity
public class User {
    @PrimaryKey public long userId;
    public String name;
    public int age;
}

@Entity
public class Library {
    @PrimaryKey public long libraryId;
    public long userOwnerId;
}

If we want to load all data we have two options:

1. @Embedded and @Relation

By adding this class:

public class UserAndLibrary {
    @Embedded public User user;
    @Relation(
         parentColumn = "userId",
         entityColumn = "userOwnerId"
    )
    public Library library;
}

And add DAO method:

@Transaction
@Query("SELECT * FROM User")
public List<UserAndLibrary> getUsersAndLibraries();

More information in Android Documentation

2. @DatabaseView

@DatabaseView("SELECT user.id, user.name, user.age, " +
              "library.libraryId FROM user " +
              "INNER JOIN library ON user.userId = library.libraryId)
public class UserAndLibrary {
    public long userId;
    public String name;
    public int age;
    public long libraryId;
 }

and a associating

@Database(entities = {User.class, Library.class},
          views = {UserAndLibrary.class},
          version = 1)
public abstract class AppDatabase extends RoomDatabase {
    public abstract UserDao userDao();
}

What is the difference between two options?

golkarm
  • 1,021
  • 1
  • 11
  • 22
  • A dirty explanation: A view is just a set generated by a SQL query that stays in memory (RAM, not disk) and a relation defines that two entities are related. @Relation takes care of indicating that one key from one enitity is a foreign key of another entity so when you query data that takes info from both entities you get the full suitable result – Some random IT boy Mar 15 '21 at 07:40
  • In my question both of them returns all data, in one of them as a list that each of them contains two object. and in the other all data is are saved in its variables – golkarm Mar 15 '21 at 07:56
  • The difference is that one reads from the disk every-time and the other one just reads once and keeps in RAM – Some random IT boy Mar 15 '21 at 08:26
  • @SomerandomITboy which one reads from disk every time, and which one reads just once? – Sourav Kannantha B Nov 09 '21 at 10:23

0 Answers0