You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Realm迁移:如何将现有对象导入新UserFooList类

Realm Migration: Migrate Favorite Foo Entries to New UserFooList & Remove the Favorite Field

Alright, I get it—you’re working with a production Realm instance and need to safely migrate your data: moving all favorite Foo entries into a dedicated UserFooList named "favorites", then removing the now-unused favorite field from Foo. Let’s walk through exactly how to implement this migration step by step.

Step 1: Update Your Realm Configuration

First, make sure your Realm config points to the new schema version and includes your migration logic. Increment the schema version (e.g., from 1 to 2) since we’re modifying the data model structure.

Step 2: Implement the Migration Logic

The core work happens in the RealmMigration implementation. Here’s how to handle each critical part:

  • Create the new UserFooList table structure (Realm auto-detects new models, but we need to populate it with existing data)
  • Query all Foo objects where favorite = true
  • Create a UserFooList instance named "favorites" and add those Foo entries to its items list
  • Remove the favorite field from the Foo model

Full Migration Code

RealmConfiguration config = new RealmConfiguration.Builder()
        .schemaVersion(2) // Increment this from your previous schema version
        .migration(new RealmMigration() {
            @Override
            public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
                RealmSchema schema = realm.getSchema();

                // 1. Create the new UserFooList schema if migrating from an older version
                if (oldVersion < 1) {
                    schema.create("UserFooList")
                            .addField("name", String.class)
                            .addRealmListField("items", schema.get("Foo"));
                    oldVersion++;
                }

                // 2. Migrate favorite Foo entries to the new "favorites" list
                if (oldVersion < 2) {
                    // Fetch all Foo objects marked as favorite
                    RealmResults<DynamicRealmObject> favoriteFoos = realm.where("Foo")
                            .equalTo("favorite", true)
                            .findAll();

                    // Create the dedicated "favorites" list
                    DynamicRealmObject favoritesList = realm.createObject("UserFooList");
                    favoritesList.setString("name", "favorites");

                    // Add all favorite Foos to the list's items
                    RealmList<DynamicRealmObject> items = favoritesList.getRealmList("items");
                    items.addAll(favoriteFoos);

                    // 3. Remove the no-longer-needed favorite field from Foo
                    schema.get("Foo").removeField("favorite");

                    oldVersion++;
                }
            }
        })
        .build();

// Initialize Realm with this updated configuration
Realm.setDefaultConfiguration(config);

Key Notes to Keep in Mind

  • Versioning Adjustments: Tweak the oldVersion checks to match your actual schema history. For example, if this is your first migration adding UserFooList, you might skip the oldVersion < 1 block and start directly with oldVersion < 2.
  • DynamicRealm Usage: We use DynamicRealm here because typed RealmObject classes can’t be used during migration (the schema is in flux).
  • Transaction Safety: All migration operations run in a single atomic transaction—if anything fails, Realm rolls back to the previous state automatically.

Your Model Classes (For Reference)

Original Foo Class (Pre-Migration)

public class Foo extends RealmObject{ 
    private String title; 
    private boolean favorite; 

    public String getTitle() { return title; } 
    public void setTitle(String title) { this.title = title; } 
    public boolean isFavorite() { return favorite; } 
    public void setFavorite(boolean favorite) { this.favorite = favorite; } 
}

Modified Foo Class (Post-Migration)

public class Foo extends RealmObject{ 
    private String title; 

    public String getTitle() { return title; } 
    public void setTitle(String title) { this.title = title; } 
}

New UserFooList Class

public class UserFooList extends RealmObject{ 
    private String name; 
    private RealmList<Foo> items; 

    public String getName() { return name; } 
    public void setName(String name) { this.name = name; } 
    public RealmList<Foo> getItems() { return items; } 
    public void setItems(RealmList<Foo> items) { this.items = items; } 
}

内容的提问来源于stack exchange,提问作者pauminku

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:48:28