I have a class entity as below
@Entity public class Task { private String name; private Integer ParentId; private Integer userId; @Ignore private int noOfSubTask; }
in DAO class there is a method getTaskList()
@Dao public interface TaskDao extends Dao<Task> { @Query("SELECT *,(SELECT count(*) FROM Task b WHERE a._id = b.ParentId ) AS noOfSubTask FROM Task a ") LiveData<List<Task>> getTaskList(); }
I want to fill noOfSubTask with the number given by (SELECT count(*) FROM Task b WHERE a._id = b.ParentId ) portion of query, but problem is it is not a column so room library does not map it getTaskList method in dao implementation (auto-generated) class.
Is there any way to fill non column field of entity (like noOfSubTask in my case) using any method of dao class of room library?
A Room entity includes fields for each column in the corresponding table in the database, including one or more columns that comprise the primary key. The following code is an example of a simple entity that defines a User table with columns for ID, first name, and last name: Kotlin Java.
Data Access Objects are the main classes where you define your database interactions. They can include a variety of query methods. The class marked with @Dao should either be an interface or an abstract class. At compile time, Room will generate an implementation of this class when it is referenced by a Database .
I faced the same problem a few days ago and had a look at this thread. I am using Kotlin data
classes for creating database entities. Given that Kotlin data classes do not play well with inheritance subclassing was not a viable option. My solution was to use the @Embedded
keyword in a wrapping class, as follows:
data class TaskToDisplay(@Embedded var task: Task, var noOfSubTask: Int = 0)
This solution does not create an additional column in the database and most importantly matches all Task's fields with Room's response columns.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With