Adding a new table to room database
To add a new table to a Room database in Android, you can follow these steps:
- Create a new entity class: Create a new Java class that represents the new table. This class should extend the
@Entity
annotation from the Room persistence library.
For example, let's say you want to add a new table called "Book" with columns for "id", "title", and "author". You would create a new Java class called Book.java
:
@Entity
public class Book {
@PrimaryKey(autoGenerate = true)
private int id;
private String title;
private String author;
// Getters and setters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
- Add the new entity to the Room database: In your Room database class, add the new entity to the
@Database
annotation.
For example, let's say your Room database class is called MyDatabase.java
:
@Database(entities = {Book.class}, version = 1)
public abstract class MyDatabase extends RoomDatabase {
//...
}
- Create a new DAO for the new table: Create a new Java class that extends the
@Dao
annotation from the Room persistence library. This class will provide methods for interacting with the new table.
For example, let's say you want to create a DAO for the "Book" table:
@Dao
public interface BookDao {
@Insert
void insertBook(Book book);
@Query("SELECT * FROM book")
List<Book> getAllBooks();
@Query("SELECT * FROM book WHERE id = :id")
Book getBookById(int id);
@Delete
void deleteBook(Book book);
}
- Update the Room database configuration: Update the Room database configuration to include the new entity and DAO.
For example, let's say your Room database configuration is stored in a file called room_database_config.xml
:
<?xml version="1.0" encoding="utf-8"?>
<room-database xmlns:android="http://schemas.android.com/apk/res/android"
android:allowMainThreadQueries="true"
android:entities="@array/entities"
android:versionCode="1">
<entity class="com.example.Book" />
</room-database>
- Rebuild and reinstall the app: Rebuild and reinstall the app to apply the changes to the Room database.
That's it! You should now have a new table in your Room database.