如何从 Hive box 对象中获取 key 并将其映射到对象的特定字段?

How to get key from Hive box object and map it to specific field of the object?

框自动递增。

假设我有一个这样的对象:

@HiveType(...)
class Dummy {
  
  @HiveField(0)
  int id;

  @HiveField(1)
  String name;

}

我希望 Hive 反序列化将 Dummy 对象的键映射到 id 字段。

如果您从 HiveObject 继承了 class,那么您可以使用内置的 属性 'key'。

    @HiveType(...)
    class Dummy extends HiveObject{
      //id not needed anymore
   
      @HiveField(0)
      String name;
    
    }
    
    ...
    
    Box<Dummy> db = Hive.box<Dummy>('dummy');
    Dummy dummy = Dummy(name: "some text");
    db.add(dummy); //add assigns next integer as key

    //after storing object to a database, you can access its key using 'key' property
    int id = dummy.key;

    //another advantage of extending HiveObject, is that you can store or delete object from the database without accessing the box:
    dummy.name = "other text";
    dummy.save(); //put modified object into box
    dummy.delete(); //delete object from the database