简体   繁体   中英

Search query using Android room relation

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()
)

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);

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.

use @DB or @Query.

That should perfectly work...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM