realm的学习

realm是一个跨平台移动数据库引擎,支持iOS、OS X(Objective-C和Swift)以及Android。

为了彻底解决性能问题,核心数据引擎C++打造的MVCC 数据库(MVCC 指的是多版本并发控制,并不是建立在SQLite之上的ORM。如果对数据引擎实现想深入了解可以查看:Realm 核心数据库引擎探秘。因此得到的收益就是比普通的ORM要快很多,甚至比单独无封装的SQLite还要快。这具体快多少的数据有人做过实验,可网上搜索。

相比SQLite,Realm更快并且具有很多现代数据库的特性,比如支持JSON,流式api,数据变更通知,以及加密支持,这些都为开发者带来了方便。

我认为靠谱的使用或者在现有项目上替换方式是抽象层+特性开关,这样降低耦合性,方便日后替换成任何数据库。

多数情况下把数据存在磁盘上的数据库文件中。发起一个从持久化机制(比如 ORM 或者 Core Data)中获取数据的请求,数据格式会是和本地平台密切相关的。持久化机制会把请求转换成一系列的 SQL 语句,创建一个数据库连接(如果没有创建的话),发送到磁盘上,执行查询,读取命中查询的每一行的数据,然后存到内存里(这里有内存消耗)。之后你需要把数据序列化成可在内存里面存储的格式,(比特对齐),CPU 才能处理它们。数据需要转换成语言层面的类型,然后它会以对象的形式返回,这样平台才能用(POJO, NSManagedObject 等等)来处理它。

Realm 跳过了拷贝过程,因为数据库文件是 memory-mapped。Realm 在访问文件偏移的时候就好像文件已经在内存中一样,实际上不是,而是虚拟内存。这是个 Realm 核心文件格式的重要设计决定。它允许文件能在没有做任何反序列化的情况下可以在内存中读取。

Realm 跳过了所有这些开销很大的步骤,而这些步骤在传统的持久化机制中必须执行。Realm 只需要简单地计算偏移来找到文件中的数据,然后从原始访问点返回数据结构(POJO/NSManagedObject/等等)的值 。有效而且更快。

realm的文档地址(https://realm.io/docs/java/latest/),有demo,有简介。

托管realm对象和非托管realm对象。Realm.copyFromRealm()Realm.copyToRealm()

继承RealmObject对象或者实现RealmModel接口

public class Product extends RealmObject {
    @PrimaryKey
    private long productId;        // 商品ID

    private String title;          // 商品标题

    private double price;          // 商品价格

    private String image;          // 商品图片

    private long vshopId;

    private boolean collect;       // 是否收藏

    public long getProductId() {
        return productId;
    }

    public void setProductId(long productId) {
        this.productId = productId;
    }

    public String getTitle() {
        return title;
    }

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

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public long getVshopId() {
        return vshopId;
    }

    public void setVshopId(long vshopId) {
        this.vshopId = vshopId;
    }

    public boolean isCollect() {
        return collect;
    }

    public void setCollect(boolean collect) {
        this.collect = collect;
    }

    @Override
    public String toString() {
        return "Product{" +
                "productId=" + productId +
                ", title=" + title +
                ", price=" + price +
                ", image=" + image +
                ", vshopId=" + vshopId +
                ", collect=" + collect +
                '}';
    }
}
public class ProductRealmProxy extends Product implements RealmObjectProxy, ProductRealmProxyInterface {
    private final ProductRealmProxy.ProductColumnInfo columnInfo;
    private final ProxyState proxyState;
    private static final List<String> FIELD_NAMES;

    ProductRealmProxy(ColumnInfo columnInfo) {
        this.columnInfo = (ProductRealmProxy.ProductColumnInfo)columnInfo;
        this.proxyState = new ProxyState(Product.class, this);
    }

    public long realmGet$productId() {
        this.proxyState.getRealm$realm().checkIfValid();
        return this.proxyState.getRow$realm().getLong(this.columnInfo.productIdIndex);
    }

    public void realmSet$productId(long value) {
        this.proxyState.getRealm$realm().checkIfValid();
        this.proxyState.getRow$realm().setLong(this.columnInfo.productIdIndex, value);
    }

    public String realmGet$title() {
        this.proxyState.getRealm$realm().checkIfValid();
        return this.proxyState.getRow$realm().getString(this.columnInfo.titleIndex);
    }

    public void realmSet$title(String value) {
        this.proxyState.getRealm$realm().checkIfValid();
        if(value == null) {
            this.proxyState.getRow$realm().setNull(this.columnInfo.titleIndex);
        } else {
            this.proxyState.getRow$realm().setString(this.columnInfo.titleIndex, value);
        }
    }

    public double realmGet$price() {
        this.proxyState.getRealm$realm().checkIfValid();
        return this.proxyState.getRow$realm().getDouble(this.columnInfo.priceIndex);
    }

    public void realmSet$price(double value) {
        this.proxyState.getRealm$realm().checkIfValid();
        this.proxyState.getRow$realm().setDouble(this.columnInfo.priceIndex, value);
    }

    public String realmGet$image() {
        this.proxyState.getRealm$realm().checkIfValid();
        return this.proxyState.getRow$realm().getString(this.columnInfo.imageIndex);
    }

    public void realmSet$image(String value) {
        this.proxyState.getRealm$realm().checkIfValid();
        if(value == null) {
            this.proxyState.getRow$realm().setNull(this.columnInfo.imageIndex);
        } else {
            this.proxyState.getRow$realm().setString(this.columnInfo.imageIndex, value);
        }
    }

    public long realmGet$vshopId() {
        this.proxyState.getRealm$realm().checkIfValid();
        return this.proxyState.getRow$realm().getLong(this.columnInfo.vshopIdIndex);
    }

    public void realmSet$vshopId(long value) {
        this.proxyState.getRealm$realm().checkIfValid();
        this.proxyState.getRow$realm().setLong(this.columnInfo.vshopIdIndex, value);
    }

    public boolean realmGet$collect() {
        this.proxyState.getRealm$realm().checkIfValid();
        return this.proxyState.getRow$realm().getBoolean(this.columnInfo.collectIndex);
    }

    public void realmSet$collect(boolean value) {
        this.proxyState.getRealm$realm().checkIfValid();
        this.proxyState.getRow$realm().setBoolean(this.columnInfo.collectIndex, value);
    }

    public static Table initTable(ImplicitTransaction transaction) {
        if(!transaction.hasTable("class_Product")) {
            Table table = transaction.getTable("class_Product");
            table.addColumn(RealmFieldType.INTEGER, "productId", false);
            table.addColumn(RealmFieldType.STRING, "title", true);
            table.addColumn(RealmFieldType.DOUBLE, "price", false);
            table.addColumn(RealmFieldType.STRING, "image", true);
            table.addColumn(RealmFieldType.INTEGER, "vshopId", false);
            table.addColumn(RealmFieldType.BOOLEAN, "collect", false);
            table.addSearchIndex(table.getColumnIndex("productId"));
            table.setPrimaryKey("productId");
            return table;
        } else {
            return transaction.getTable("class_Product");
        }
    }

    public static ProductRealmProxy.ProductColumnInfo validateTable(ImplicitTransaction transaction) {
        if(!transaction.hasTable("class_Product")) {
            throw new RealmMigrationNeededException(transaction.getPath(), "The Product class is missing from the schema for this Realm.");
        } else {
            Table table = transaction.getTable("class_Product");
            if(table.getColumnCount() != 6L) {
                throw new RealmMigrationNeededException(transaction.getPath(), "Field count does not match - expected 6 but was " + table.getColumnCount());
            } else {
                HashMap columnTypes = new HashMap();

                for(long columnInfo = 0L; columnInfo < 6L; ++columnInfo) {
                    columnTypes.put(table.getColumnName(columnInfo), table.getColumnType(columnInfo));
                }

                ProductRealmProxy.ProductColumnInfo var5 = new ProductRealmProxy.ProductColumnInfo(transaction.getPath(), table);
                if(!columnTypes.containsKey("productId")) {
                    throw new RealmMigrationNeededException(transaction.getPath(), "Missing field \'productId\' in existing Realm file. Either remove field or migrate using io.realm.internal.Table.addColumn().");
                } else if(columnTypes.get("productId") != RealmFieldType.INTEGER) {
                    throw new RealmMigrationNeededException(transaction.getPath(), "Invalid type \'long\' for field \'productId\' in existing Realm file.");
                } else if(table.isColumnNullable(var5.productIdIndex) && table.findFirstNull(var5.productIdIndex) != -1L) {
                    throw new IllegalStateException("Cannot migrate an object with null value in field \'productId\'. Either maintain the same type for primary key field \'productId\', or remove the object with null value before migration.");
                } else if(table.getPrimaryKey() != table.getColumnIndex("productId")) {
                    throw new RealmMigrationNeededException(transaction.getPath(), "Primary key not defined for field \'productId\' in existing Realm file. Add @PrimaryKey.");
                } else if(!table.hasSearchIndex(table.getColumnIndex("productId"))) {
                    throw new RealmMigrationNeededException(transaction.getPath(), "Index not defined for field \'productId\' in existing Realm file. Either set @Index or migrate using io.realm.internal.Table.removeSearchIndex().");
                } else if(!columnTypes.containsKey("title")) {
                    throw new RealmMigrationNeededException(transaction.getPath(), "Missing field \'title\' in existing Realm file. Either remove field or migrate using io.realm.internal.Table.addColumn().");
                } else if(columnTypes.get("title") != RealmFieldType.STRING) {
                    throw new RealmMigrationNeededException(transaction.getPath(), "Invalid type \'String\' for field \'title\' in existing Realm file.");
                } else if(!table.isColumnNullable(var5.titleIndex)) {
                    throw new RealmMigrationNeededException(transaction.getPath(), "Field \'title\' is required. Either set @Required to field \'title\' or migrate using RealmObjectSchema.setNullable().");
                } else if(!columnTypes.containsKey("price")) {
                    throw new RealmMigrationNeededException(transaction.getPath(), "Missing field \'price\' in existing Realm file. Either remove field or migrate using io.realm.internal.Table.addColumn().");
                } else if(columnTypes.get("price") != RealmFieldType.DOUBLE) {
                    throw new RealmMigrationNeededException(transaction.getPath(), "Invalid type \'double\' for field \'price\' in existing Realm file.");
                } else if(table.isColumnNullable(var5.priceIndex)) {
                    throw new RealmMigrationNeededException(transaction.getPath(), "Field \'price\' does support null values in the existing Realm file. Use corresponding boxed type for field \'price\' or migrate using RealmObjectSchema.setNullable().");
                } else if(!columnTypes.containsKey("image")) {
                    throw new RealmMigrationNeededException(transaction.getPath(), "Missing field \'image\' in existing Realm file. Either remove field or migrate using io.realm.internal.Table.addColumn().");
                } else if(columnTypes.get("image") != RealmFieldType.STRING) {
                    throw new RealmMigrationNeededException(transaction.getPath(), "Invalid type \'String\' for field \'image\' in existing Realm file.");
                } else if(!table.isColumnNullable(var5.imageIndex)) {
                    throw new RealmMigrationNeededException(transaction.getPath(), "Field \'image\' is required. Either set @Required to field \'image\' or migrate using RealmObjectSchema.setNullable().");
                } else if(!columnTypes.containsKey("vshopId")) {
                    throw new RealmMigrationNeededException(transaction.getPath(), "Missing field \'vshopId\' in existing Realm file. Either remove field or migrate using io.realm.internal.Table.addColumn().");
                } else if(columnTypes.get("vshopId") != RealmFieldType.INTEGER) {
                    throw new RealmMigrationNeededException(transaction.getPath(), "Invalid type \'long\' for field \'vshopId\' in existing Realm file.");
                } else if(table.isColumnNullable(var5.vshopIdIndex)) {
                    throw new RealmMigrationNeededException(transaction.getPath(), "Field \'vshopId\' does support null values in the existing Realm file. Use corresponding boxed type for field \'vshopId\' or migrate using RealmObjectSchema.setNullable().");
                } else if(!columnTypes.containsKey("collect")) {
                    throw new RealmMigrationNeededException(transaction.getPath(), "Missing field \'collect\' in existing Realm file. Either remove field or migrate using io.realm.internal.Table.addColumn().");
                } else if(columnTypes.get("collect") != RealmFieldType.BOOLEAN) {
                    throw new RealmMigrationNeededException(transaction.getPath(), "Invalid type \'boolean\' for field \'collect\' in existing Realm file.");
                } else if(table.isColumnNullable(var5.collectIndex)) {
                    throw new RealmMigrationNeededException(transaction.getPath(), "Field \'collect\' does support null values in the existing Realm file. Use corresponding boxed type for field \'collect\' or migrate using RealmObjectSchema.setNullable().");
                } else {
                    return var5;
                }
            }
        }
    }

    public static String getTableName() {
        return "class_Product";
    }

    public static List<String> getFieldNames() {
        return FIELD_NAMES;
    }

    public static Product createOrUpdateUsingJsonObject(Realm realm, JSONObject json, boolean update) throws JSONException {
        ProductRealmProxy obj = null;
        if(update) {
            Table table = realm.getTable(Product.class);
            long pkColumnIndex = table.getPrimaryKey();
            long rowIndex = -1L;
            if(!json.isNull("productId")) {
                rowIndex = table.findFirstLong(pkColumnIndex, json.getLong("productId"));
            }

            if(rowIndex != -1L) {
                obj = new ProductRealmProxy(realm.schema.getColumnInfo(Product.class));
                ((RealmObjectProxy)obj).realmGet$proxyState().setRealm$realm(realm);
                ((RealmObjectProxy)obj).realmGet$proxyState().setRow$realm(table.getUncheckedRow(rowIndex));
            }
        }

        if(obj == null) {
            if(json.has("productId")) {
                if(json.isNull("productId")) {
                    obj = (ProductRealmProxy)realm.createObject(Product.class, (Object)null);
                } else {
                    obj = (ProductRealmProxy)realm.createObject(Product.class, Long.valueOf(json.getLong("productId")));
                }
            } else {
                obj = (ProductRealmProxy)realm.createObject(Product.class);
            }
        }

        if(json.has("productId")) {
            if(json.isNull("productId")) {
                throw new IllegalArgumentException("Trying to set non-nullable field productId to null.");
            }

            ((ProductRealmProxyInterface)obj).realmSet$productId(json.getLong("productId"));
        }

        if(json.has("title")) {
            if(json.isNull("title")) {
                ((ProductRealmProxyInterface)obj).realmSet$title((String)null);
            } else {
                ((ProductRealmProxyInterface)obj).realmSet$title(json.getString("title"));
            }
        }

        if(json.has("price")) {
            if(json.isNull("price")) {
                throw new IllegalArgumentException("Trying to set non-nullable field price to null.");
            }

            ((ProductRealmProxyInterface)obj).realmSet$price(json.getDouble("price"));
        }

        if(json.has("image")) {
            if(json.isNull("image")) {
                ((ProductRealmProxyInterface)obj).realmSet$image((String)null);
            } else {
                ((ProductRealmProxyInterface)obj).realmSet$image(json.getString("image"));
            }
        }

        if(json.has("vshopId")) {
            if(json.isNull("vshopId")) {
                throw new IllegalArgumentException("Trying to set non-nullable field vshopId to null.");
            }

            ((ProductRealmProxyInterface)obj).realmSet$vshopId(json.getLong("vshopId"));
        }

        if(json.has("collect")) {
            if(json.isNull("collect")) {
                throw new IllegalArgumentException("Trying to set non-nullable field collect to null.");
            }

            ((ProductRealmProxyInterface)obj).realmSet$collect(json.getBoolean("collect"));
        }

        return obj;
    }

    public static Product createUsingJsonStream(Realm realm, JsonReader reader) throws IOException {
        Product obj = (Product)realm.createObject(Product.class);
        reader.beginObject();

        while(reader.hasNext()) {
            String name = reader.nextName();
            if(name.equals("productId")) {
                if(reader.peek() == JsonToken.NULL) {
                    reader.skipValue();
                    throw new IllegalArgumentException("Trying to set non-nullable field productId to null.");
                }

                ((ProductRealmProxyInterface)obj).realmSet$productId(reader.nextLong());
            } else if(name.equals("title")) {
                if(reader.peek() == JsonToken.NULL) {
                    reader.skipValue();
                    ((ProductRealmProxyInterface)obj).realmSet$title((String)null);
                } else {
                    ((ProductRealmProxyInterface)obj).realmSet$title(reader.nextString());
                }
            } else if(name.equals("price")) {
                if(reader.peek() == JsonToken.NULL) {
                    reader.skipValue();
                    throw new IllegalArgumentException("Trying to set non-nullable field price to null.");
                }

                ((ProductRealmProxyInterface)obj).realmSet$price(reader.nextDouble());
            } else if(name.equals("image")) {
                if(reader.peek() == JsonToken.NULL) {
                    reader.skipValue();
                    ((ProductRealmProxyInterface)obj).realmSet$image((String)null);
                } else {
                    ((ProductRealmProxyInterface)obj).realmSet$image(reader.nextString());
                }
            } else if(name.equals("vshopId")) {
                if(reader.peek() == JsonToken.NULL) {
                    reader.skipValue();
                    throw new IllegalArgumentException("Trying to set non-nullable field vshopId to null.");
                }

                ((ProductRealmProxyInterface)obj).realmSet$vshopId(reader.nextLong());
            } else if(name.equals("collect")) {
                if(reader.peek() == JsonToken.NULL) {
                    reader.skipValue();
                    throw new IllegalArgumentException("Trying to set non-nullable field collect to null.");
                }

                ((ProductRealmProxyInterface)obj).realmSet$collect(reader.nextBoolean());
            } else {
                reader.skipValue();
            }
        }

        reader.endObject();
        return obj;
    }

    public static Product copyOrUpdate(Realm realm, Product object, boolean update, Map<RealmModel, RealmObjectProxy> cache) {
        if(object instanceof RealmObjectProxy && ((RealmObjectProxy)object).realmGet$proxyState().getRealm$realm() != null && ((RealmObjectProxy)object).realmGet$proxyState().getRealm$realm().threadId != realm.threadId) {
            throw new IllegalArgumentException("Objects which belong to Realm instances in other threads cannot be copied into this Realm instance.");
        } else if(object instanceof RealmObjectProxy && ((RealmObjectProxy)object).realmGet$proxyState().getRealm$realm() != null && ((RealmObjectProxy)object).realmGet$proxyState().getRealm$realm().getPath().equals(realm.getPath())) {
            return object;
        } else {
            ProductRealmProxy realmObject = null;
            boolean canUpdate = update;
            if(update) {
                Table table = realm.getTable(Product.class);
                long pkColumnIndex = table.getPrimaryKey();
                long rowIndex = table.findFirstLong(pkColumnIndex, ((ProductRealmProxyInterface)object).realmGet$productId());
                if(rowIndex != -1L) {
                    realmObject = new ProductRealmProxy(realm.schema.getColumnInfo(Product.class));
                    ((RealmObjectProxy)realmObject).realmGet$proxyState().setRealm$realm(realm);
                    ((RealmObjectProxy)realmObject).realmGet$proxyState().setRow$realm(table.getUncheckedRow(rowIndex));
                    cache.put(object, (RealmObjectProxy)realmObject);
                } else {
                    canUpdate = false;
                }
            }

            return canUpdate?update(realm, realmObject, object, cache):copy(realm, object, update, cache);
        }
    }

    public static Product copy(Realm realm, Product newObject, boolean update, Map<RealmModel, RealmObjectProxy> cache) {
        Product realmObject = (Product)realm.createObject(Product.class, Long.valueOf(((ProductRealmProxyInterface)newObject).realmGet$productId()));
        cache.put(newObject, (RealmObjectProxy)realmObject);
        ((ProductRealmProxyInterface)realmObject).realmSet$productId(((ProductRealmProxyInterface)newObject).realmGet$productId());
        ((ProductRealmProxyInterface)realmObject).realmSet$title(((ProductRealmProxyInterface)newObject).realmGet$title());
        ((ProductRealmProxyInterface)realmObject).realmSet$price(((ProductRealmProxyInterface)newObject).realmGet$price());
        ((ProductRealmProxyInterface)realmObject).realmSet$image(((ProductRealmProxyInterface)newObject).realmGet$image());
        ((ProductRealmProxyInterface)realmObject).realmSet$vshopId(((ProductRealmProxyInterface)newObject).realmGet$vshopId());
        ((ProductRealmProxyInterface)realmObject).realmSet$collect(((ProductRealmProxyInterface)newObject).realmGet$collect());
        return realmObject;
    }

    public static Product createDetachedCopy(Product realmObject, int currentDepth, int maxDepth, Map<RealmModel, CacheData<RealmModel>> cache) {
        if(currentDepth <= maxDepth && realmObject != null) {
            CacheData cachedObject = (CacheData)cache.get(realmObject);
            Product unmanagedObject;
            if(cachedObject != null) {
                if(currentDepth >= cachedObject.minDepth) {
                    return (Product)cachedObject.object;
                }

                unmanagedObject = (Product)cachedObject.object;
                cachedObject.minDepth = currentDepth;
            } else {
                unmanagedObject = new Product();
                cache.put(realmObject, new CacheData(currentDepth, unmanagedObject));
            }

            ((ProductRealmProxyInterface)unmanagedObject).realmSet$productId(((ProductRealmProxyInterface)realmObject).realmGet$productId());
            ((ProductRealmProxyInterface)unmanagedObject).realmSet$title(((ProductRealmProxyInterface)realmObject).realmGet$title());
            ((ProductRealmProxyInterface)unmanagedObject).realmSet$price(((ProductRealmProxyInterface)realmObject).realmGet$price());
            ((ProductRealmProxyInterface)unmanagedObject).realmSet$image(((ProductRealmProxyInterface)realmObject).realmGet$image());
            ((ProductRealmProxyInterface)unmanagedObject).realmSet$vshopId(((ProductRealmProxyInterface)realmObject).realmGet$vshopId());
            ((ProductRealmProxyInterface)unmanagedObject).realmSet$collect(((ProductRealmProxyInterface)realmObject).realmGet$collect());
            return unmanagedObject;
        } else {
            return null;
        }
    }

    static Product update(Realm realm, Product realmObject, Product newObject, Map<RealmModel, RealmObjectProxy> cache) {
        ((ProductRealmProxyInterface)realmObject).realmSet$title(((ProductRealmProxyInterface)newObject).realmGet$title());
        ((ProductRealmProxyInterface)realmObject).realmSet$price(((ProductRealmProxyInterface)newObject).realmGet$price());
        ((ProductRealmProxyInterface)realmObject).realmSet$image(((ProductRealmProxyInterface)newObject).realmGet$image());
        ((ProductRealmProxyInterface)realmObject).realmSet$vshopId(((ProductRealmProxyInterface)newObject).realmGet$vshopId());
        ((ProductRealmProxyInterface)realmObject).realmSet$collect(((ProductRealmProxyInterface)newObject).realmGet$collect());
        return realmObject;
    }

    public ProxyState realmGet$proxyState() {
        return this.proxyState;
    }

    public int hashCode() {
        String realmName = this.proxyState.getRealm$realm().getPath();
        String tableName = this.proxyState.getRow$realm().getTable().getName();
        long rowIndex = this.proxyState.getRow$realm().getIndex();
        byte result = 17;
        int result1 = 31 * result + (realmName != null?realmName.hashCode():0);
        result1 = 31 * result1 + (tableName != null?tableName.hashCode():0);
        result1 = 31 * result1 + (int)(rowIndex ^ rowIndex >>> 32);
        return result1;
    }

    public boolean equals(Object o) {
        if(this == o) {
            return true;
        } else if(o != null && this.getClass() == o.getClass()) {
            ProductRealmProxy aProduct = (ProductRealmProxy)o;
            String path = this.proxyState.getRealm$realm().getPath();
            String otherPath = aProduct.proxyState.getRealm$realm().getPath();
            if(path != null) {
                if(!path.equals(otherPath)) {
                    return false;
                }
            } else if(otherPath != null) {
                return false;
            }

            label30: {
                String tableName = this.proxyState.getRow$realm().getTable().getName();
                String otherTableName = aProduct.proxyState.getRow$realm().getTable().getName();
                if(tableName != null) {
                    if(tableName.equals(otherTableName)) {
                        break label30;
                    }
                } else if(otherTableName == null) {
                    break label30;
                }

                return false;
            }

            if(this.proxyState.getRow$realm().getIndex() != aProduct.proxyState.getRow$realm().getIndex()) {
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }

    static {
        ArrayList fieldNames = new ArrayList();
        fieldNames.add("productId");
        fieldNames.add("title");
        fieldNames.add("price");
        fieldNames.add("image");
        fieldNames.add("vshopId");
        fieldNames.add("collect");
        FIELD_NAMES = Collections.unmodifiableList(fieldNames);
    }

    static final class ProductColumnInfo extends ColumnInfo {
        public final long productIdIndex;
        public final long titleIndex;
        public final long priceIndex;
        public final long imageIndex;
        public final long vshopIdIndex;
        public final long collectIndex;

        ProductColumnInfo(String path, Table table) {
            HashMap indicesMap = new HashMap(6);
            this.productIdIndex = this.getValidColumnIndex(path, table, "Product", "productId");
            indicesMap.put("productId", Long.valueOf(this.productIdIndex));
            this.titleIndex = this.getValidColumnIndex(path, table, "Product", "title");
            indicesMap.put("title", Long.valueOf(this.titleIndex));
            this.priceIndex = this.getValidColumnIndex(path, table, "Product", "price");
            indicesMap.put("price", Long.valueOf(this.priceIndex));
            this.imageIndex = this.getValidColumnIndex(path, table, "Product", "image");
            indicesMap.put("image", Long.valueOf(this.imageIndex));
            this.vshopIdIndex = this.getValidColumnIndex(path, table, "Product", "vshopId");
            indicesMap.put("vshopId", Long.valueOf(this.vshopIdIndex));
            this.collectIndex = this.getValidColumnIndex(path, table, "Product", "collect");
            indicesMap.put("collect", Long.valueOf(this.collectIndex));
            this.setIndicesMap(indicesMap);
        }
    }
}

realmGet$xxx() 和 realmSet$xxx()是和realm数据库打交道的。

在从 Realm 实例中获取任何 Realm 对象的时候(比如调用 Realm.createObject() 或者 RealmQuery.findFirst()),你实际上是获取了这个对象相应的 Realm 代理对象。对其属性的访问实际上都是通过相应生成的方法来访问底层的 Realm 数据库来实现的。

在查询返回Realm 对象的时候,这些对象的属性并没有被拷贝到 Java 堆中,这使得 Realm 的查询非常得快。这些属性只在需要被访问的时候,才经由生成的 getter 方法加载。

realm 通过引用计数控制的,所以要及时关闭。

https://realm.io/docs/上介绍够全,如果遇到问题,就去stackoverflow提问吧。






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值