数据库dao层数据库访问层_室—数据访问对象(DAO)

数据库dao层数据库访问层

Note: This article is part of the advanced Room series which covers all the details about the Room persistence library. You can read all the articles here:

注意:本文是高级Room系列的一部分,该系列涵盖有关Room持久性库的所有详细信息。 您可以在此处阅读所有文章:

室—数据访问对象(DAO) (Room — Data Access Objects(DAO))

In previous articles, we have covered how we can use Room persistence library to create a relational database very easily. Some of the advantages of using Room are compile-time query verification, no boilerplate code and easy integration with RxJava, LiveData and Kotlin Coroutines. All these advantages in Room are achieved using Data Access Objects or DAOs.

在先前的文章中,我们介绍了如何使用Room Persistence库轻松地创建关系数据库。 使用Room的一些优点是编译时查询验证,无需样板代码以及易于与RxJava,LiveData和Kotlin Coroutines集成。 使用数据访问对象或DAO可以实现Room中的所有这些优点。

In this article, we going to discuss Data Access Objects or DAOs in detail.

在本文中,我们将详细讨论Data Access ObjectsDAOs

In Room, Data Access Objects or DAOs are used to access your application’s persisted data. They are a better and modular way to access your database as compared to query builders or direct queries.

在会议室中, Data Access ObjectsDAOs用于访问应用程序的持久数据。 与查询构建器或直接查询相比,它们是访问数据库的更好的模块化方式。

A DAO can be either an interface or an abstract class. If it’s an abstract class, it can optionally have a constructor that takes a RoomDatabase as its only parameter. Room creates each DAO implementation at compile time.

DAO可以是接口或抽象类。 如果它是抽象类,则可以选择具有一个将RoomDatabase作为其唯一参数的构造函数。 Room会在编译时创建每个DAO实现。

You can perform multiple operations using DAO like Insertion, Updation, Deletion and making raw queries. Also, you can easily integrate LiveData, RxJava Observables, Kotlin Coroutines in DAOs.

您可以使用DAO执行多种操作,例如插入,更新,删除和进行原始查询。 另外,您可以轻松地在DAO中集成LiveData,RxJava Observables和Kotlin协程。

插入 (Insertion)

When you create a DAO method and annotate it with @Insert, Room generates an implementation that inserts all parameters into the database in a single transaction.

创建DAO方法并使用@Insert对其进行注释时,Room会生成一个实现,该实现将所有参数插入到单个事务中。

@Dao
interface UserDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertUsers(vararg users: User)
    @Insert
    fun insertBothUsers(user1: User, user2: User)
    @Insert
    fun insertUsersAndFriends(user: User, friends: List<User>)
}

onConflict annotation parameter signifies what to do if a conflict happens on insertion. It can take the following values:

onConflict批注参数表示如果插入时发生冲突,该怎么办。 它可以采用以下值:

  • OnConflictStrategy.REPLACE : To replace the old data and continue the transaction.

    OnConflictStrategy.REPLACE :替换旧数据并继续进行事务。

  • OnConflictStrategy.ROLLBACK : To rollback the transaction.

    OnConflictStrategy.ROLLBACK :回滚事务。

  • OnConflictStrategy.ABORT : To abort the transaction. The transaction is rolled back.

    OnConflictStrategy.ABORT :中止事务。 事务回滚。

  • OnConflictStrategy.FAIL : To fail the transaction. The transaction is rolled back.

    OnConflictStrategy.FAIL :使事务失败。 事务回滚。

  • OnConflictStrategy.NONE : To ignore the conflict.

    OnConflictStrategy.NONE :忽略冲突。

Note: ROLLBACK and FAIL strategies are deprecated. Use ABORT instead.

注意:不建议使用ROLLBACKFAIL策略。 请改用ABORT

更新中 (Updation)

When you create a DAO method and annotate it with @Update, Room generates an implementation that modifies a set of entities, given as parameters, in the database. It uses a query that matches against the primary key of each entity.

创建DAO方法并使用@ Update对其进行注释时,Room会生成一个实现,该实现会修改数据库中作为参数给出的一组实体。 它使用与每个实体的主键匹配的查询。

@Dao
interface UserDao {
    @Update(onConflict = OnConflictStrategy.REPLACE)
    fun updateUsers(vararg users: User)
    @Update
    fun update(user: User)
}

删除中 (Deletion)

When you create a DAO method and annotate it with @Delete, Room generates an implementation that removes a set of entities, given as parameters, from the database. It uses the primary keys to find the entities to delete.

当你创建一个DAO方法,并对其进行批注@ D elete ,房间生成给出参数,消除一组实体的实现,从数据库中。 它使用主键来查找要删除的实体。

@Dao
interface UserDao {
    @Delete
    fun deleteUsers(vararg users: User)
}

简单查询 (Simple queries)

@Query is the main annotation used in DAO classes. It allows you to perform read/write operations on a database. Each @Query method is verified at compile time, so if there is a problem with the query, a compilation error occurs instead of a runtime failure.

@Query是DAO类中使用的主要注释。 它允许您对数据库执行读/写操作。 每个@Query方法都在编译时进行验证,因此,如果查询存在问题,则会发生编译错误,而不是运行时错误。

Room also verifies the return value of the query such that if the name of the field in the returned object doesn’t match the corresponding column names in the query response, Room alerts you in one of the following two ways:

Room还会验证查询的返回值,以便如果返回的对象中的字段名称与查询响应中的相应列名称不匹配,Room可以通过以下两种方式之一向您发出警报:

  • It gives a warning if only some field names match.

    如果仅某些字段名称匹配,则会发出警告。
  • It gives an error if no field names match.

    如果没有匹配的字段名称,则会产生错误。
@Dao
interface UserDao {
    @Query("SELECT * FROM users")
    fun loadAllUsers(): Array<User>
}

Passing parameters into the query

将参数传递到查询中

Parameters passed to the DAO methods can be used into the query written in @Query annotation.

传递给DAO方法的参数可用于以@Query注释编写的查询中。

@Dao
interface UserDao {
    @Query("SELECT * FROM users WHERE age BETWEEN :minAge AND :maxAge")
    fun loadAllUsersBetweenAges(minAge: Int, maxAge: Int): Array<User>


    @Query("SELECT * FROM users WHERE first_name LIKE :search " +
           "OR last_name LIKE :search")
    fun findUserWithName(search: String): List<User>
}

Returning subsets of columns

返回列的子集

You can also return subsets of columns from a query in Room.

您还可以从Room中的查询返回列的子集。

data class NameTuple(
    @ColumnInfo(name = "first_name") val firstName: String?,
    @ColumnInfo(name = "last_name") val lastName: String?
)
@Dao
interface UserDao {
    @Query("SELECT first_name, last_name FROM users")
    fun loadFullName(): List<NameTuple>
}

Direct cursor access

直接光标访问

If your app’s logic requires direct access to the return rows, you can return a Cursor object from your queries.

如果您的应用程序逻辑要求直接访问返回行,则可以从查询中返回Cursor对象。

@Dao
interface UserDao {
    @Query("SELECT * FROM users")
    fun loadAllUsers(): Cursor
}

Querying multiple tables

查询多个表

Some of your queries might require access to multiple tables to calculate the result. Room allows you to write any query, so you can also join tables. Furthermore, if the response is an observable data type, such as Flowable or LiveData, Room watches all tables referenced in the query for invalidation.

您的某些查询可能需要访问多个表才能计算结果。 Room允许您编写任何查询,因此您也可以联接表。 此外,如果响应是可观察到的数据类型,如FlowableLiveData室手表在查询为无效引用的所有表。

@Dao
interface BookDao {
    @Query(
        "SELECT * FROM book " +
        "INNER JOIN loan ON loan.book_id = book.id " +
        "INNER JOIN user ON user.id = loan.user_id " +
        "WHERE users.name LIKE :userName"
    )
    fun findBooksBorrowedByNameSync(userName: String): List<Book>
}

查询返回类型 (Query return types)

Room supports a variety of return types for query methods, including specialised return types for interoperability with specific frameworks or APIs.

Room支持各种查询方法的返回类型,包括用于与特定框架或API互操作性的特殊返回类型。

Image for post

You can return LiveData, Observable and Flow from query methods. Also, you can make a DAO method suspend function. These are discussed in separate articles.

您可以从查询方法返回LiveDataObservableFlow 。 另外,您可以使DAO方法暂停函数 。 这些将在单独的文章中讨论。

Thank You!!!

谢谢!!!

翻译自: https://medium.com/mindorks/data-access-objects-dao-in-room-3d108d6b4b54

数据库dao层数据库访问层

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值