如何避免Realm重写/覆盖子对象?

时间:2018-04-13 14:29:18

标签: java android realm

我有对象

public class RProfile extends RealmObject {
    @PrimaryKey
    @Required
    String id;
    String title;
    String description;
}

另一个obj

public class RChatMessage extends RealmObject {
        @PrimaryKey
        @Required
        String id;
        String message;
        RProfile sender;
    }
  1. 从服务器我得到我的个人资料

    {"id":"131231","title":"My Profile","description","Any description"}

    并将其写入Realm:

    public void saveOrUpdateItem(RProfile item) { realm.insertOrUpdate(item); }

  2. 之后,从服务器我得到这样的聊天消息:

    {"id":"131231","message":"Any Message","sender":{"id":"131231","title":"My Profile"}}

    并将其写入Realm:

    public void saveOrUpdateItem(RChatMessage item) { realm.insertOrUpdate(item); }

  3. 但是当我尝试从领域获取RProfile时,它没有字段description description == null ),因为当我写了RChatMessageRProfile被覆盖了。

    如何避免这种行为?

1 个答案:

答案 0 :(得分:2)

正如您所说,第一个回复类型为" RProfile":

>> % Define a number
>> num = 67

num =

    67

>> % Get type of variable num
>> class(num)

ans =

    'double'

>> % Define character vector
>> myName = 'Rishikesh Agrawani'

myName =

    'Rishikesh Agrwani'

>> % Check type of myName
>> class(myName)

ans =

    'char'

>> % Define a cell array
>> cellArr = {'This ', 'is ', 'a ', 'big chance to learn ', 'MATLAB.'}; % Cell array
>> 
>> class(cellArr)

ans =

    'cell'

>> % Get more details including type
>> whos num
  Name      Size            Bytes  Class     Attributes

  num       1x1                 8  double              

>> whos myName
  Name        Size            Bytes  Class    Attributes

  myName      1x17               34  char               

>> whos cellArr
  Name         Size            Bytes  Class    Attributes

  cellArr      1x5               634  cell               

>> % Another way to use whos i.e using whos(char_vector)
>> whos('cellArr')
  Name         Size            Bytes  Class    Attributes

  cellArr      1x5               634  cell               

>> whos('num')
  Name      Size            Bytes  Class     Attributes

  num       1x1                 8  double              

>> whos('myName')
  Name        Size            Bytes  Class    Attributes

  myName      1x17               34  char               

>> 

第二个回复的类型为" RChatMessage":

{
  "id": "131231",
  "title": "My Profile",
  "description": "Any description"
}


public void saveOrUpdateItem(RProfile item) {
       realm.insertOrUpdate(item);
}

现在,如果您尝试使用以下方法将数据保存到本地数据库中:

{
  "id": "131231",
  "message": "Any Message",
  "sender": {
    "id": "131231",
    "title": "My Profile"
  }
}

当您使用领域的insertOrUpdatefunction时,它将更新数据。

您可以按照以下两种方法之一进行操作:

  1. 使用realm.insert(item)方法。它将插入数据,如果已经找到,则不会更新任何值。

  2. 另一种方法可能是首先匹配并获取RProfile的描述,然后从已保存的Model中添加描述,然后在RChatMessage模型上执行insertOrUpdate。

    public void saveOrUpdateItem(RChatMessage item) {
           realm.insertOrUpdate(item);
    }
    
  3. P.S。您需要相应地创建setter和getter才能使此代码正常工作。