有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

域中ID的java自定义方法以支持自动增量行为

我曾经使用过realm版本0.80,我知道realm不支持自动增量行为
因此,我做了以下变通:

public class Item extends RealmObject implements Serializable {

@PrimaryKey
private int id;
private int order;

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public int getOrder() {
    return order;
}

public void setOrder(int order) {
    id = Increment.Primary_Cart(order); //this line for increment id
    this.order = order;
}

这是我增加id的静态方法:

public static int Primary_Cart(int id){
    if(id>0) {
        id_Cart++;
    }
    return id_Cart;
}

在我决定将Realm从版本0.80.0升级到0.90.1之前,一切都很好
然后我犯了一个错误:

Caused by: io.realm.exceptions.RealmPrimaryKeyConstraintException: Value already exists: 0

更清楚地说,我使用Realm解析JSON,有些模型没有ID,这就是我使用上述解决方案的原因,我不想使用GSON之类的其他解决方案
因为我有一个巨大的项目,所以我只需要使用领域来进行解析和存储,我想对它进行优化


共 (1) 个答案

  1. # 1 楼答案

    现在Realm不支持自动增量功能,但carloseduardosx的这一要点可能对您有用:https://gist.github.com/carloseduardosx/a7bd88d7337660cd10a2c5dcc580ebd0

    它是一个专门为领域数据库实现自动增量的类。这并不复杂,mosr的相关部分包括以下两种方法:

    /**
     * Search in modelMap for the last saved id from model passed and return the next one
     *
     * @param clazz Model to search the last id
     * @return The next id which can be saved in database for that model, 
     * {@code null} will be returned when this method is called by reflection
     */
    public Integer getNextIdFromModel(Class<? extends RealmObject> clazz) {
    
        if (isValidMethodCall()) {
            AtomicInteger modelId = modelMap.get(clazz);
            if (modelId == null) {
                return 0;
            }
            return modelId.incrementAndGet();
        }
        return null;
    }
    
    /**
     * Utility method to validate if the method is called from reflection,
     * in this case is considered a not valid call otherwise is a valid call
     *
     * @return The boolean which define if the method call is valid or not
     */
    private boolean isValidMethodCall() {
        StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
        for (StackTraceElement stackTraceElement : stackTraceElements) {
    
            if (stackTraceElement.getMethodName().equals("newInstance")) {
                return false;
            }
        }
        return true;
    }