简体   繁体   English

如何正确保存包含RealmList的对象?

[英]How to properly save object that contains RealmList?

I have 2 realm objects: Unit and Subunit. 我有2个领域对象:单位和子单位。 Unit object has a realm list of subunits. 单元对象具有子单元的领域列表。 I work with single Unit object. 我使用单个Unit对象。 Periodically a new Subunit object is created and added to Unit's list, and then I call copyToRealmOrUpdate on my Unit object. 定期创建一个新的Subunit对象,并将其添加到Unit的列表中,然后在Unit对象上调用copyToRealmOrUpdate。 However, every time I call copyToRealmOrUpdate, all the Subunits that Unit contains get copied again even if they already exist in database. 但是,每次我调用copyToRealmOrUpdate时,即使该单元中包含的所有子单元已经存在于数据库中,也会再次被复制。 This causes my database to grow in size quickly. 这导致我的数据库大小迅速增加。 Is there a way to save only last Subunit that was added to list every time I save Unit object? 有没有办法只保存每次保存Unit对象时添加到列表中的最后一个Subunit? Thanks 谢谢

Try this code for creating new Subunit instances: 尝试使用以下代码来创建新的Subunit实例:

realm.beginTransaction();

Unit unit = realm.where(Unit.class)
                 // write your condition for extracting of Unit object
                 .equalTo("id", unit_id).findFirst();

if(unit == null){
    Log.e(APP_TAG, "Unit " + unit_id + " not found");
    realm.cancelTransaction();
    return;
}

Subunit subunit = realm.createObject(Subunit.class);
// setup subunit fields

unit.getSubunits().add(subunit);

realm.commitTransaction();

Instead of creating Unit object every time your need to get this from realm by particular query and put Subunit instance directly to query object. 您无需每次都通过特定查询从领域中获取此对象并将Subunit实例直接放入查询对象中,而无需每次创建Unit对象。

  1. Create one Unit -Object and save it with copyToRealmOrUpdate in database. 创建一个Unit Object并将其与copyToRealmOrUpdate保存在数据库中。
  2. When you create new Subunit , save him with copyToRealmOrUpdate in database. 创建新的Subunit ,将其与copyToRealmOrUpdate一起copyToRealmOrUpdate在数据库中。
  3. Then you can call Unit -Object, that is already saved in database, and with Unit.getSubunits().add(Subunit) you add saved Subunit in database to saved Unit in database. 然后,您可以调用已保存在数据库中的Unit -Object,并使用Unit.getSubunits().add(Subunit)将数据库中已保存的Subunit添加到数据库中已保存的Unit中。

You don't need save Unit many times in database. 您不需要在数据库中多次保存Unit

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

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