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

1.Entity

2.DAO(Data Access Object)

3.Database

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

import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;

@Entity
public class Student {

@PrimaryKey(autoGenerate = true)
int id;

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

public void setName(String name)
{
this.name = name;
}
public String getname()
{
return name;
}
public void setId(int id)
{
this.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

@Dao
interface accessstudent
{
@Insert
public void insertrecord(Student student);

@Delete
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)
.fallbackToDestructiveMigration()
.build();
}
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;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread th = new Thread(Mainclass.this);
th.start();
}
@Override
public void run() {
Databaseclass db = Databaseclass.getInstance(getApplicationContext());
Student sa = new Student();
sa.setName("Pandiyan");
db.getstudent().insertrecord(sa);

List<Student> sab = db.getstudent().getStudent();
for(Student name:sab)
{
System.out.println("Name--"+name.getname());
}
}
}