CodeNewbie Community 🌱

Cover image for Room database. Basic entities in Java
Tristan
Tristan

Posted on

Room database. Basic entities in Java

Introduction

  • This series is going to be where I put all my Android notes. As I learn something new about Android development I will put in this tutorial series
  • Read the full documentation HERE

What is Room?

  • The Room persistence library provides an abstraction layer over SQLite to allow for more robust database access while harnessing the fill power of SQLite.

What is SQLite?

  • As the official SQLite documentation states, do not be mislead by the lite in the name. SQLite is a full featured SQL implementation. This means that basically all the same rules and queries you can do with SQL you can also do with SQLite. So terms like table,row or column mean the exact same thing as any other SQL based database

  • However, using SQLite can result in a lot of boiler plate code that is tedious and error prone. That is where Room comes to the rescue. Room's entire job is the make working with SQLite a whole lot easier.

Defining entities

  • What is an entity? Well, when using the Room persistence library we define entities to represent the objects that we want to store. Each entity corresponds to a table in the associated Room database, and each instance of an entity represents a row of data in the corresponding table. We define an entity by annotating any Java class with the @Entity annotation:
@Entity(tableName = "calves")
public class Calf {

    @PrimaryKey(autoGenerate = true)
    private Long id;

    @NonNull
    @ColumnInfo(name="tag_number")
    public String tagNumber;

//Constructor, getters and setters below
}

Enter fullscreen mode Exit fullscreen mode
  • When we use the @Entity annotation all the fields in the class are now mapped to columns in the database table. Each entity that we define must also have at least one field annotated with the @PrimaryKey annotation. This field must be unique as it will act as the identifier in the underlying SQLite database. Notice that I have autoGenerate = true in the primary key field. This tells Android that we want the SQLite database to handle the generation of this unique field, which is great because then we do not have to deal with super complex code trying to keep the id unique.
  • You can also notice that we use @ColumnInfo(name="tag_number") to change the name of the column and @Entity(tableName = "calves") to change the whole table's name in the database.
  • Now we have both created a simple and easy to use database Entity with Room

Conclusion

  • Thank you for taking the time out of your day to read this blog post of mine. If you have any questions or concerns please comment below or reach out to me on Twitter.

Top comments (0)