RoomDB

**ROOM DB**

1. Room is an Android Architecture component.
2. It provides an abstraction Layer over SQLite.
3. Easy caching of relavent piece of data.

**Components of ROOM**

1. Entity :

 1. An Entity Defines schema of database tables, Each table is defined by an entity.
 2. Entity class is Annoted with @Entity.
 3. It contains the getters and setters for the field of the database.
 4. By default Room uses the class name as the tableName , If you want a table to have a different name, set the tableName property of the @Entity annotation.
 5. By default Room uses the field names as the Column names in the database , If you want a column to have a different name, add the @ColumnInfo annotation to a field.
 6. Entity class must have atleast 1 primary key.
  
  Example :  @Entity(tableName = "User") //tableName value is case sensitive.
     class Users{
     
      @PrimaryKey
      private String id;
    
      @ColumnInfo(name = "first_name")
      private String firstName; //To change the column name for particular field use columnInfo
      
      //Getters and Setters
     }
  
2. Dao :

 1. It contains method to access database.
 2. It provides an API for reading and writing the data into an database.
 3. It is an abstract class or Interface.
 4. Room creates each DAO implementation at compile time.
 5. It is Annoted with @Dao.
  
  Example :  @Dao
     public interface UsersDao {
     
      @Insert
      public void insertUser(Users users);
      
      @Query("select * from users")
      public void List<Users> FetchUsers();
      
      @Update
      public void updateUsers(Users users);
      
      @Delete
      public void deleteUsers(Users users);
      
     }
  
  
3. Database :

 1. It is a Database holder class and serves as the main access point for the underlined connection of our apps for persistence and Relational database.
 2. It must be an Abstract class that extends RoomDatabase.
 3. It is Annoted with @Database and have annotation properties (Entities and Version).
 4. Contains an abstract method that has 0 argument and returns an object of Dao.
 5. At runtime, you can Acquire an instance of Database by calling Room.databaseBuilder() or Room.inMemoryDatabaseBuilder().
 6. Database class should be singleton.
  
  Example :  @Database(entities = Users.class, version = 1)
  
     public abstract class UserDataBase extends RoomDatabase {
     
     public abstract UsersDao usersDao();
     
     //make NoteRoomDataBase as singleton class and acquire instance of DB using Room.databaseBuilder()
     
     }

Comments

Popular posts from this blog

How to Delete Commented code througout the project in Android Studio

How to Generate Key Hash for FaceBook Integration

Crypto Exchanger