Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill non column field of entity in room library

Tags:

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?

like image 610
Kevan Avatar asked Nov 14 '17 09:11

Kevan


People also ask

What is entity in Room?

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.

What is DAO in android?

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 .


1 Answers

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.

like image 94
mtsahakis Avatar answered Sep 28 '22 14:09

mtsahakis