Android – Room Persistence Library

1. Room database là gì?

Room là một Persistence Library được google giới thiệu trong sự kiện google I/O mới đây, nó là một abstract layer cung cấp cách thức truy câp thao tác với dữ liệu trong cơ sở dữ liệu SQLite. Các thành phần: Database, DAO (Data Access Object) và Entity.

Các ứng dụng sử dụng một lượng lớn dữ liệu có cấu trúc có thể hưởng lợi lớn từ việc lưu lại dữ liệu trên local thông qua Room Database. Trường hợp thường gặp nhất là chỉ cache những dữ liệu có liên quan. Nếu làm vậy thì khi thiết bị không có kết nối internet thì user vẫn có thể truy cập data đấy khi đang offline. Mọi dữ liệu được phát sinh hay thay đổi do user sau đó sẽ được đồng bộ với server khi họ online trở lại.

Room Database đơn giản hóa việc mã hóa và giảm thiểu các hoạt động liên quan đến cơ sở dữ liệu. Nếu các bạn đã chán ngán với việc phải khai báo các câu lệnh rất dài mới có thể xây dựng được database thì hãy sử dụng Room ngay nhé!

2. Đặc điểm của Room database

  • Trong trường hợp SQLite, Không có xác minh thời gian biên dịch của các truy vấn SQLite thô. Nhưng trong Room có ​​xác thực SQL tại thời điểm biên dịch.
  • Khi lược đồ của bạn thay đổi, bạn cần cập nhật các truy vấn SQL bị ảnh hưởng theo cách thủ công. Room giải quyết vấn đề này.
  • Bạn cần sử dụng nhiều mã soạn sẵn để chuyển đổi giữa các truy vấn SQL và các Data objects. Tuy nhiên, Room ánh xạ các đối tượng cơ sở dữ liệu của chúng tôi tới Data objects mà không cần mã soạn sẵn.
  • Room được xây dựng để hoạt động với LiveData để quan sát dữ liệu, trong khi SQLite thì không.

3. Cách import Room

Mở build.gradle (app) và thêm dòng lệnh sau:

dependencies {
    def room_version = "2.4.0"

    implementation "androidx.room:room-runtime:$room_version"
    annotationProcessor "androidx.room:room-compiler:$room_version"

    // optional - RxJava2 support for Room
    implementation "androidx.room:room-rxjava2:$room_version"

    // optional - RxJava3 support for Room
    implementation "androidx.room:room-rxjava3:$room_version"

    // optional - Guava support for Room, including Optional and ListenableFuture
    implementation "androidx.room:room-guava:$room_version"

    // optional - Test helpers
    testImplementation "androidx.room:room-testing:$room_version"

    // optional - Paging 3 Integration
    implementation "androidx.room:room-paging:2.4.0"
}

4. Các thành phần chính trong Room

Có 3 thành phần chính trong Room:

  • Database

Có thể dùng componenet này để tạo database holder. Annotation sẽ cung cấp danh sách các thực thể và nội dung class sẽ định nghĩa danh sách các DAO (đối tượng truy cập CSDL) của CSDL. Nó cũng là điểm truy cập chính cho các kết nối phía dưới.

@Database(
    entities = [
        School::class,
        Student::class
    ],
    version = 2,
    exportSchema = false
)
abstract class SchoolDataBase : RoomDatabase() {

    abstract fun schoolDAO(): ISchoolDAO

    abstract fun studentDAO(): IStudentDAO

    companion object {
        @Volatile
        private var INSTANCE: SchoolDataBase? = null

        fun getInstance(context: Context): SchoolDataBase = INSTANCE ?: synchronized(this) {
            return Room.databaseBuilder(
                context.applicationContext,
                SchoolDataBase::class.java,
                Constant.SCHOOL_DATABASE
            ).build().also {
                INSTANCE = it
            }
        }
    }
}
  • Entity

Component này đại diện cho một class chứa một row của database. Với mỗi một entity thì một database table sẽ được tạo để giữ các items tương ứng. Nên tham chiếu lớp enity thông qua mảng entities trong class Database.

Mỗi Object phải xác định ít nhất 1 trường làm khóa chính. Ngay cả khi chỉ có 1 trường, bạn vẫn cần chú thích trường này bằng anotation @PrimaryKey. Ngoài ra, nếu bạn muốn Room gán ID tự động cho các thực thể, bạn có thể đặt thuộc tính autoGenerate của @PrimaryKey.(Trường hợp thuộc tính là int, long).

@Entity(tableName = SCHOOL_TABLE)
data class School(
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = SCHOOL_ID)
    val schoolId: Int = 0,
    @ColumnInfo(name = SCHOOL_NAME)
    val schoolName: String,
    @ColumnInfo(name = SCHOOL_ADDRESS)
    val schoolAddress: String
)

Trường hợp các bạn muốn đánh index cho một số trường trong database để tăng tốc độ truy vấn các bạn có thể sử dụng như sau:

@Entity(indices = {@Index(value = {"first_name", "last_name"}})

Định nghĩa foreignKeys. Ví dụ bạn có đối tượng khác là Student và bạn có thể định nghĩa relationship tới đối tượng School thông qua @ForeignKey annotation như sau:

@Entity(
    tableName = STUDENT_TABLE,
    foreignKeys = [ForeignKey(
        entity = School::class,
        parentColumns = [SCHOOL_ID],
        childColumns = [SCHOOL_ID],
        onDelete = ForeignKey.CASCADE

    )]
)
data class Student(
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = STUDENT_ID)
    val studentId: Int = 0,
    @ColumnInfo(name = SCHOOL_ID)
    val schoolId: Int,
    @ColumnInfo(name = STUDENT_NAME)
    val studentName: String,
    @ColumnInfo(name = STUDENT_GRADE)
    val studentGrade: Float
)
  • DAO (Data Access Object)

Đây là component đại diện cho lớp hoặc interface như một đối tượng truy cập dữ liệu (DAO). DAO là thành phần chính của Room là chịu trách nhiệm trong việc định nghĩa các phương thức truy cập CSDL.

@Dao
interface ISchoolDAO {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertSchool(school: School)

    @Delete
    suspend fun deleteSchool(school: School)


    @Update
    suspend fun updateSchool(school: School)    

    @Transaction
    @Query("SELECT * FROM $SCHOOL_TABLE")
    fun getAllSchool(): Flow<List<SchoolAndStudent>>
}

5. Kết luận

Trên đây là phần giới thiệu cơ bản về Room database của mình.

Cám ơn các bạn đã đọc bài viết của mình.

Tham khảo: https://developer.android.com/training/data-storage/room#groovy


Posted

in

by

Tags:

Comments

24 responses to “Android – Room Persistence Library”

  1. rikvip Avatar

    I think what you typed was very reasonable.
    However, think on this, suppose you added a little
    content? I am not suggesting your information is not good,
    however what if you added a headline to possibly grab folk’s attention? I mean Android – Room Persistence Library
    – techover.io is a little boring. You should look
    at Yahoo’s front page and see how they create article titles to grab people to open the links.
    You might add a video or a pic or two to get readers interested
    about everything’ve got to say. Just my opinion, it would bring
    your website a little bit more interesting.

  2. hit club Avatar

    Excellent blog here! Also your web site loads up very fast!
    What web host are you using? Can I get your affiliate link to your host?
    I wish my website loaded up as quickly as yours
    lol

  3. b52 club Avatar

    Some truly interesting points you have written.Assisted me a lot, just what
    I was looking for :D.

  4. yo88 Avatar

    There’s certainly a lot to know about this topic. I love all the points you have made.

  5. sunwin Avatar

    If you want to obtain a great deal from this paragraph then you have to apply such techniques to
    your won blog.

  6. 789club Avatar

    You have brought up a very excellent details, regards for the post.

  7. 789club Avatar

    I like the helpful information you provide in your articles.
    I will bookmark your weblog and check again here frequently.
    I am quite certain I will learn many new stuff right here! Good luck
    for the next!

  8. rikvip Avatar

    I’m not sure why but this website is loading incredibly slow for me.
    Is anyone else having this problem or is it a problem on my end?
    I’ll check back later and see if the problem
    still exists.

  9. kết quả xổ số miền bắc hôm nay Avatar

    Excellent post.Ne’er knew this, thanks for letting me know.

  10. go88 Avatar

    I think you have noted some very interesting points,
    appreciate it for the post.

  11. rikvip Avatar

    Hi just wanted to give you a quick heads up and let you
    know a few of the pictures aren’t loading correctly.
    I’m not sure why but I think its a linking issue.

    I’ve tried it in two different browsers and both show the same
    results.

  12. 789club Avatar

    Wohh just what I was searching for, appreciate it for posting.

  13. hit club Avatar

    Sweet blog! I found it while searching on Yahoo News.
    Do you have any suggestions on how to get listed in Yahoo News?

    I’ve been trying for a while but I never seem to get there!
    Thanks

  14. sunwin Avatar

    This is the perfect site for anyone who wishes to understand this topic.
    You realize so much its almost tough to argue with you (not
    that I personally will need to…HaHa). You definitely put a brand new spin on a topic that’s been written about for decades.
    Great stuff, just great!

  15. top game bài Avatar

    I am very happy to read this. This is the type of manual that needs to be given and not
    the accidental misinformation that is at the other blogs.
    Appreciate your sharing this best doc.

  16. topzo Avatar

    Nice post. I learn something totally new and challenging on sites I
    stumbleupon everyday. It will always be helpful to read
    through content from other authors and practice something from their
    web sites.

  17. 789club Avatar

    Some really nice and utilitarian information on this internet site, likewise I think the design and
    style contains superb features.

  18. go88 Avatar

    I like this weblog very much, Its a very nice place to read and
    get information.

  19. rikvip Avatar

    Oh my goodness! Awesome article dude! Thanks, However I am going through problems with your RSS.
    I don?t understand the reason why I cannot join it. Is there anybody getting identical RSS
    problems? Anyone who knows the answer will you kindly respond?
    Thanx!!

  20. 789club Avatar

    Have you ever thought about creating an e-book or guest authoring on other blogs?
    I have a blog based upon on the same information you discuss
    and would love to have you share some stories/information. I know my subscribers would value your work.
    If you’re even remotely interested, feel free to shoot me an e mail.

  21. Code of destiny Avatar

    I’m extremely impressed together with your writing abilities as neatly as with the structure to your blog. Is this a paid theme or did you modify it your self? Either way stay up the nice quality writing, it’s uncommon to see a nice weblog like this one nowadays!

  22. sunwin Avatar

    Hi there, just became aware of your blog through Google, and found that
    it’s really informative. I am going to watch out for brussels.

    I will appreciate if you continue this in future.
    Many people will be benefited from your writing.

    Cheers!

  23. 789club Avatar

    I conceive this website holds some real great info for everyone :D.

  24. yo88 Avatar

    Hi there everyone, it’s my first go to see at this website,
    and paragraph is actually fruitful designed for me, keep
    up posting these types of content.

Leave a Reply to yo88 Cancel reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: