Room Database

What is Room Database?

Its an abstraction layer over Sqlite which provide full access over database

Object Relation Mapping(ORM) library that mean it map our database object to our java object.

Component of Room Database


2.DAO(Data Access Object)


1.Entity → create a table within a database if we annote @Entity to the top of the class it will create a table within database.

@PrimarKey is used to define its unique ,the sqlite will create a unique id for the mentioned column if we decalre autogenerate = true inside the PrimaryKey

@ColumnInfo(name = “columnname”) will give information about the particullar column we can mention the column name inside ColumnInfo


public class Student {

@PrimaryKey(autoGenerate = true)
int id;

@ColumnInfo(name = "name")
String name;

public void setName(String name)
{ = name;
public String getname()
return name;
public void setId(int id)
{ = id;
public int getId()
return id;

2.DAO(Data Access Object)

Where we access database function such as insert,delete and update.

we will create an interface with @DAO annotation for accessing database

interface accessstudent
public void insertrecord(Student student);

public void deleterecord(Student student);

@Query("Select * from Student")
public List<Student> getStudent();

DataBase where we define our entities,tablename and DAO and we make this class as abstract which extends RoomDatabase and we use singleton pattern for creating instance with static variable so it can accessed in main class without creating object just by class name.

@Database(entities = Student.class,exportSchema = false,version = 1)
public abstract class Databaseclass extends RoomDatabase {

public static final String DB_name = "Student_db";
private static Databaseclass instance = null;

public static synchronized Databaseclass getInstance(Context ctx)
if(instance == null)
instance = Room.databaseBuilder(ctx.getApplicationContext(),Databaseclass.class,DB_name)
return instance;

public abstract accessstudent getstudent();

the .fallbackToDestructiveMigration() will destroy and create the table inside database

Calling from main class

public class Mainclass extends AppCompatActivity implements Runnable {

Button button_start,button_stop;
protected void onCreate(@Nullable Bundle savedInstanceState) {
Thread th = new Thread(Mainclass.this);
public void run() {
Databaseclass db = Databaseclass.getInstance(getApplicationContext());
Student sa = new Student();

List<Student> sab = db.getstudent().getStudent();
for(Student name:sab)