0% found this document useful (0 votes)
2 views

Lecture 8

SQLite is a lightweight, serverless relational database engine used in Android for persistent local storage and structured data management. Room is an abstraction layer over SQLite that simplifies database management, reduces boilerplate code, and supports real-time updates with LiveData and Flow. The document covers CRUD operations, challenges with SQLite, and provides guidance on setting up and using Room, including defining entities, DAOs, and handling database migrations.

Uploaded by

ukr.droid.dev
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lecture 8

SQLite is a lightweight, serverless relational database engine used in Android for persistent local storage and structured data management. Room is an abstraction layer over SQLite that simplifies database management, reduces boilerplate code, and supports real-time updates with LiveData and Flow. The document covers CRUD operations, challenges with SQLite, and provides guidance on setting up and using Room, including defining entities, DAOs, and handling database migrations.

Uploaded by

ukr.droid.dev
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Sqlite.

Room

Author:Semen Naduiev
Introduction to SQLite

What is SQLite?

● SQLite is a lightweight, relational database engine used in Android.


● It is serverless, self-contained, and requires minimal configuration.

Why we use SQLite in Android?

● Provides persistent local storage.


● Supported natively in Android.
● Useful for storing structured data.
Features of SQLite

ACID-compliant.

Single-file database.

Supports standard SQL queries.

When to use SQLite in Android apps?

● When the app needs structured data storage.


● When local persistence is required without an internet connection.
Working with SQLite
CRUD Operations
Challenges with SQLite

Requires a lot of boilerplate code.

Manual management of database migrations.

Risk of SQL injection without proper escaping.


Introduction to Room

What is Room?

● An abstraction layer over SQLite for better database management.


● Provides compile-time verification of queries.

Why use Room instead of raw SQLite?

● Reduces boilerplate code.


● Supports LiveData and Flow for real-time updates.
● Manages database migrations efficiently.
Setting Up Room

implementation "androidx.room:room-runtime:latest-version"

kapt "androidx.room:room-compiler:latest-version"

or add ksp
Basic Entity Definition

Each entity is a data class annotated with @Entity:


Table Name Customization

By default, Room uses the class name as the table name, but you can change it using tableName:
Primary Key in Room

A Primary Key is a unique identifier for each record in a database table. In Room, every Entity (table) must have at
least one field marked as a primary key.

Declaring a Primary Key

To define a primary key, use the @PrimaryKey annotation:

Here, the id uniquely identifies each record in the Note table.


Auto-Generating a Primary Key

If you want Room to generate the id automatically, set autoGenerate = true:


Why is a Primary Key Important?

✔ Ensures uniqueness of records.

✔ Optimizes searches and lookups.

✔ Facilitates relationships between tables.

✔ Allows Room to manage data efficiently.


Column Customization

You can specify column names explicitly to avoid conflicts:


Unique Constraints in Room

A Unique Constraint ensures that a column (or a combination of columns) contains unique values across all rows in a table. This helps prevent duplicate entries in a database.

Defining Unique Constraints on a Single Column

You can enforce uniqueness using the @Index annotation with unique = true:

How does it work?

The email column must be unique for all users.

If you try to insert a duplicate email, Room will throw an SQLite constraint exception.
Unique Constraints on Multiple Columns

To enforce uniqueness across multiple columns (composite unique constraint):


Embedded Objects’

You can store objects within an entity using @Embedded:


Ignore Fields

To exclude certain fields from the database, use @Ignore:


Creating a DAO (Data Access Object) in Room

A DAO (Data Access Object) is an interface that provides methods to interact with the database.
It allows you to insert, update, delete, and query data using annotations instead of writing raw
SQL queries.
Defining a DAO

A DAO is defined as an interface or an abstract class with methods annotated with @Insert,
@Update, @Delete, and @Query.

How does it work?

@Insert: Adds a new user to the database.

@Update: Updates an existing user.

@Delete: Removes a user.

@Query: Fetches a user by ID using raw SQL.


Handling Conflicts with @Insert

By default, @Insert throws an error if a duplicate entry is inserted. You can handle this using onConflict strategies:

@Insert(onConflict = OnConflictStrategy.REPLACE)

fun insertUser(user: User)

✔ REPLACE: If a duplicate exists, it will replace the old entry.

✔ IGNORE: If a duplicate exists, it will skip the insert and return -1.

✔ ABORT (default): Throws an error if a conflict occurs.


Inserting Multiple Items at Once
Update (@Update)

Used to modify existing records. Room generates an UPDATE SQL statement based on the
primary key.
Delete (@Delete)

Used to remove records from the database.


Query (@Query)

Allows you to execute custom SQL queries to read data from the database.
Transactions (@Transaction)

If multiple database operations must succeed together, use transactions.


Creating a Table
Data Types in SQLite

Unlike traditional SQL databases, SQLite is dynamically typed, meaning that it does not enforce
strict data types for columns. However, it does support five storage classes that define how data
is stored.
Querying Data
To retrieve data from a table, use the SELECT statement.
Joins in SQLite (Combining Tables)

In SQLite, joins allow you to combine rows from two or more tables based on a related column
between them. Joins are essential for querying data spread across multiple tables, ensuring that
relational data can be linked effectively.

SQLite supports different types of joins:

1. INNER JOIN
2. LEFT JOIN (or LEFT OUTER JOIN)
3. CROSS JOIN
4. SELF JOIN
5. RIGHT JOIN (SQLite does not support this directly)
INNER JOIN

INNER JOIN returns only the rows where there is a match in both tables.
Example:
We have two tables, users and orders, and we want to get the list of users and their orders.
LEFT JOIN (LEFT OUTER JOIN)

LEFT JOIN returns all rows from the left table and matched rows from the right table. If there is
no match, the result is NULL from the right table.
Example:

In this case, we want to get all users, including those without orders.
CROSS JOIN

CROSS JOIN returns the Cartesian product of two tables. This means it returns all possible
combinations of rows from both tables, without any condition.
Example:

Assume you have two tables, colors and products, and you want to pair every product with each
color.
SELF JOIN

A SELF JOIN is a join where a table is joined with itself. It is often used to compare rows within
the same table.
Example:

Let’s assume we have a employees table, where employees report to other employees
(manager-subordinate relationship).
Setting up the Database Class

In Android development, Room provides an abstraction layer over SQLite to allow more robust
database access while leveraging SQLite’s full power. The Database class in Room is the central
point for your database configuration.
Define RoomDatabase Class

The Room Database class is where you define the database configuration and serve as the main
access point for the app's data.

You might also like