Search query using Android room relation

 ̄綄美尐妖づ 提交于 2020-06-28 06:04:30

问题


In Android room relation, is it possible to use search query using the property of the related table. Below is my table structure. In this i am relating transaction with payment and lines(transaction items). I have an search field in my UI where the user could search using payment amount which is inside payment table. How to form a query to access the properties of payment table.

class TransactionWithPaymentAndLines(
    @Embedded
    var transactions: Transactions? = null,

    @Relation(
        parentColumn = "id",
        entityColumn = "transactionId",
        entity = Payment::class
    )
    var payments: List<Payment> = listOf(),

    @Relation(
        parentColumn = "id",
        entityColumn = "transactionId",
        entity = TransactionLines::class
    )
    var transactionLines: List<TransactionLines> = listOf()
)

回答1:


Ideal way is to query multiple related tables is to create a View. A view combines data from two or more tables using join.

In Android, using Room Persistance library, you can create such a view, and then you can query the fields of view. This is how you can do it:

Suppose, you have tables:

User: id, name, departmentId

Department: id, name

Create a View:

@DatabaseView("SELECT user.id, user.name, user.departmentId," +
        "department.name AS departmentName FROM user " +
        "INNER JOIN department ON user.departmentId = department.id")
data class UserDetail(
    val id: Long,
    val name: String?,
    val departmentId: Long,
    val departmentName: String?
)

Add View to Database:

@Database(entities = arrayOf(User::class),
          views = arrayOf(UserDetail::class), version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun userDetailDao(): UserDetailDao
}

Create a DAO:

@Dao
interface UserDetailDao {
    @Query("SELECT * FROM UserDetail")
    fun loadAllUserDetails(): Array<UserDetail>
}

Now, you can query a View using this DAO.




回答2:


Absolutely possible, you can use @Query in your DAO class please read Room Database Documentation

Examples of @Query

@Query("SELECT * FROM user")
List<User> getAll();

@Query("SELECT * FROM user WHERE uid IN (:userIds)")
List<User> loadAllByIds(int[] userIds);

@Query("SELECT * FROM user WHERE first_name LIKE :first AND " +
       "last_name LIKE :last LIMIT 1")
User findByName(String first, String last);



回答3:


use @DB or @Query.

That should perfectly work...

@Query("SELECT * FROM TABLE_NAME") List getAll();



来源:https://stackoverflow.com/questions/58297705/search-query-using-android-room-relation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!