简体   繁体   中英

Merging two entities when querying in Room Database android

Let's say we have User and Order entity

@Entity
public class User{
   int id;
   String name;
}
@Entity
public class Order{
   int id;
   int userId;
   String meal;
}

So when i query

@Query("SELECT * FROM users")
public List<User> loadUsers(); 

I want this output:

{"user":{"id":"","name":"",
"order":{"id":"","userId":"","meal":""}}}

You can use Relation annotation for this problem. Note, the official documentation says [ official reference ]:

The type of the field annotated with Relation must be a List or Set.

@Entity
public class User{
   @PrimaryKey
   int id;
   String name;
   @Relation(parentColumn = "id", entityColumn = "orderId", entity = Order.class)
   List<Order> orders;
}

@Entity
public class Order{
   @PrimaryKey
   int id;
   int userId;
   String meal;
}

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