如何填充房间库中实体的非列字段 [英] How to fill non column field of entity in room library

查看:91
本文介绍了如何填充房间库中实体的非列字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下的类实体

@Entity
public class Task {    
    private String name; 
    private Integer ParentId;
    private Integer userId;   
    @Ignore
    private int noOfSubTask;
}

在DAO类中,有一个方法getTaskList()

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

我想填写 noOfSubTask,其编号由查询的(SELECT b(WHERE a._id = b.ParentId)部分)中的(SELECT count(*))给定, 但问题是它不是一列,因此房间库无法在dao实现(自动生成)类中将其映射到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.

是否有任何方法可以使用房间库的dao类的任何方法来填充实体的非列字段(如本例中的noOfSubTask)?

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?

推荐答案

几天前,我遇到了同样的问题,并对这个线程进行了研究.我正在使用Kotlin data类来创建数据库实体.鉴于Kotlin数据类不能很好地与继承子类配合使用,因此不是一个可行的选择.我的解决方案是在包装类中使用@Embedded关键字,如下所示:

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)

此解决方案不会在数据库中创建其他列,最重要的是,将所有Task的字段与Room的响应列进行匹配.

This solution does not create an additional column in the database and most importantly matches all Task's fields with Room's response columns.

这篇关于如何填充房间库中实体的非列字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆