How to fill non column field of entity in room library

前端 未结 4 1424
天命终不由人
天命终不由人 2021-02-01 21:00

I have a class entity as below

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


        
4条回答
  •  自闭症患者
    2021-02-01 21:11

    I'm using Kotlin and I've had a similar problem, and below is how I solved it.

    1. Add additional field with ?(question mark) for nullable, without @Ignore annotation

      @Entity(tableName = "task")
      data class Task (
          val name: String,
          val parentId: Integer,
          val userId: Integer,
          val noOfSubTask: Integer?
      )
      
    2. Add additional field(noOfSubTask in this case) to every query that selects Task in DAO.

      @Dao
      interface TaskDao {
          @Query("SELECT *,(SELECT count(*) FROM Task b  WHERE a._id = b.ParentId ) AS noOfSubTask FROM Task a ")
          fun getTaskList(): LiveData>
      
          @Query("SELECT *, NULL AS noOfSubTask FROM Task WHERE name = :name")
          fun getTask(name: String): LiveData
      
          ...
      }
      

    If this does not work, you can try RawQuery that was recently introduced in Google I/O 2018.

提交回复
热议问题