问题
It's possible for room to have Recursive relations? I have an Entity that can be nested in a Parent/Childs structures something like this
Category1
|_________Category2
|_________Category3
| |_________Category4
|_________Category5`
I'm copying this structure from a json that is obtained from a WebService.
This is my current Entity:
@Entity(tableName = "categories")
public class Category
{
@PrimaryKey
@NonNull
private String code;
private String name;
private String parentCode;
@Relation(parentColumn = "code", entityColumn = "parentCode", entity = Category.class)
private List<Category> childrens;
}
But during compiling I obtain a StackOverflow error:
Cause: java.lang.StackOverflowError at android.arch.persistence.room.processor.PojoProcessor.doProcess(PojoProcessor.kt:113) at android.arch.persistence.room.processor.PojoProcessor.access$doProcess(PojoProcessor.kt:74) at android.arch.persistence.room.processor.PojoProcessor$process$1.invoke(PojoProcessor.kt:105) at android.arch.persistence.room.processor.PojoProcessor$process$1.invoke(PojoProcessor.kt:74) at android.arch.persistence.room.processor.cache.Cache$Bucket.get(Cache.kt:46)
I know that I can remove the children from the Entity and iterate the json to save every Category without childrens, and later get the children by the parent code in a separate query, but I just want to know if it is possible to have a recursive Relation like the one in the code
回答1:
Short Answer: NO you can't have recursive relations.
Long Answer: Reading the Docs about Relation in Room https://developer.android.com/reference/android/arch/persistence/room/Relation I found that you can't use @Relation annotation inside a class annotated as @Entity
Note that @Relation annotation can be used only in Pojo classes, an Entity class cannot have relations. This is a design decision to avoid common pitfalls in Entity setups. You can read more about it in the main Room documentation. When loading data, you can simply work around this limitation by creating Pojo classes that extend the Entity.
来源:https://stackoverflow.com/questions/52294589/android-room-recursive-relation