简体   繁体   中英

one to many relation within same table using Android Room Database

I'm trying to create a one to many relation within the same table using Android Room Database, I'm trying to create an entity named Task which can have none or many sub Tasks which is also of type Task, The code for entity Task is as follows

package com.xxxxx.xxxxx.xxxx;


import androidx.room.Embedded;
import androidx.room.Entity;
import androidx.room.Index;
import androidx.room.PrimaryKey;



@Entity(tableName = "task_table", indices = {@Index(value = "id", unique = true)})
public class Task {

    @PrimaryKey(autoGenerate = true)
    private int id;

    private String description;

    @Embedded
    private Task parentTask;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Task getParentTask() {
        return parentTask;
    }

    public void setParentTask(Task parentTask) {
        this.parentTask = parentTask;
    }

}

when compiled an error is thrown at compile time as follows:

Recursive referencing through @Embedded and/or @Relation detected: com.xxxxx.xxxxx.xxxx.Task -> com.xxxxx.xxxxx.xxxx.Task.

Is there any another way to create one to many relationship within same table using Android Room Database?

Pardon my english it's not my first language.

Try this:

Class Task

@Entity(tableName = "task_table", indices = {@Index(value = "id", unique = true)})
public class Task {

    @PrimaryKey(autoGenerate = true)
    private int id;

    private String description;

    private Int parentId; // <- here you should put parent Id, or null if there is no parent

    ........
}

Class with Relation

public class TaskWithSubtasks{
    @Embedded
    Task task;
    
    @Relation(
        parentColumn = "id",
        entityColumn = "parentId"
    )
    List<Task> subTasks;
}

Dao method

@Query("SELECT * FROM task where id =:id")
TaskWithSubtasks getTaskWithSubTasks(int id);

PS I doubt you should expect for getting entire-level structure with the query. If you have Task with subtasks Task1 and Task2 ; and Task1 has its own subtask Task1_1 , I don't think you'll get Task1 with it subTask Task1_1 with just one query to main node - Task . Though you can try

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM