简体   繁体   English

使用 ObjectBox 存储一对多关系列表?

[英]Store list of One-To-Many relation Using ObjectBox?

I get a json like below from server:我从服务器得到一个像下面这样的 json:

  { "customers": [
    {
        "customer_name": "name1",
        "orders_list": [
            {
                "order_id": "1111111",
                "order_type": "a",
                "order_date": "11/02/2020 "
            },
            {
                "order_id": "1111112",
                "order_type": "b",
                "order_date": "11/02/2020 "
            },
            {
                "order_id": "1111113",
                "order_type": "c",
                "order_date": "11/02/2020 "
            }
        ]
    },
    //more customers
]

} }

I get it using Retrofit and want to store it with Objectbox.我使用 Retrofit 获取它并希望将它与 Objectbox 一起存储。

Customer entity:客户实体:

  @Entity
public class Customer {

    @Id long id;

    @SerializedName("customer_name")
    private String  customer_name;

    @SerializedName("array_of_matchs")
    @Transient
    public List<Order> orders_list;

    @Backlink
    public ToMany<Order> orders;

   //constructor , getters , setters ,...
}

Order Entity:订单实体:

public class Order {公共类订单{

    @Id
    public long id;

    @SerializedName("order_id")
    private int  order_id;

    @SerializedName("order_type")
    private String  order_type;

    @SerializedName("order_date")
    private String  order_date;

    public ToOne<Customer> customer;
  //constructor , getters , setters ,...
}

Gson convertor returns a List of Customer s with all his orders.I tried to store customers as below : Gson 转换器返回一个包含所有订单的Customer List 。我尝试按如下方式存储客户:

  customersBox.put(list_of_customers_get_from_retrofit);

And orders :和命令:

for (Customer each_customer : list_of_customers_get_from_retrofit ) {
      orderBox.put(each_customer.orders_list);
}

Then when i checked boxes with Data Browser ,all customerToOneRelationId s set to 0 .然后,当我使用数据浏览器选中复选框时,所有customerToOneRelationId设置为 0。 What's wrong with that?那有什么问题?

In such case, how do we make a relation between the customer and his Order s List?在这种情况下,我们如何在customer和他的Order列表之间建立关系? How to store orders in right way?如何以正确的方式存储订单?

I have to set targets manually :我必须手动设置目标:

 for (Customer each_customer : list_of_customers_get_from_retrofit ) {
     for (Order each_order : each_customer.orders_list ) {
       each_order.customer.setTarget(each_customer);
       orderBox.put(each_order);
     }
}

Thanks to this repository (This is useful for any Objectbox newbie like me).感谢这个存储库(这对像我这样的任何 Objectbox 新手都很有用)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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