Create views into a database

The Room persistence library supports SQLite database views, which let you encapsulate a query in a class. Room refers to these query-backed classes as views, and you can use them as data objects in a data access object (DAO).

Create a view

To create a view, add the @DatabaseView annotation to a class. Set the annotation value to the query that the class represents.

The following code snippet provides an example of a view:

@DatabaseView(
"""
 SELECT User.id, User.name, User.departmentId, Department.name AS departmentName
 FROM User INNER JOIN Department ON User.departmentId = Department.id
 """
)
dataclassUserDetail(
valid:Long,
valname:String?,
valdepartmentId:Long,
valdepartmentName:String?
)

Associate a view with your database

To include this view in your database, add the views property to your app's @Database annotation:

@Database(
entities=[User::class,Department::class],
views=[UserDetail::class],
version=1
)
abstractclassAppDatabase:RoomDatabase(){
abstractfunuserDao():UserDao
}

Content and code samples on this page are subject to the licenses described in the Content License. Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.

Last updated 2026年07月29日 UTC.