如何在领域android中设置主键自动增量

时间:2016-10-21 11:00:09

标签: android realm

我想为我的表设置主键自动增量。

这是我的班级。我已设置主键但我希望它是自动增量主键。

public class users extends RealmObject {

@PrimaryKey
private int id;
private long icn;
private String name;
private String email;
private String password;
private int phone;

public String getName() {
    return name;
}

public int getId() {
    return id;
}

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

public long getIcn() {
    return icn;
}

public void setIcn(long icn) {
    this.icn = icn;
}

public void setName(String name) {
    this.name = name;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public int getPhone() {
    return phone;
}

public void setPhone(int phone) {
    this.phone = phone;
}

}

先谢谢。

8 个答案:

答案 0 :(得分:37)

在交易中,您始终可以可靠地访问当前最大ID,您可以根据该ID增加该ID并将其用作下一个ID的基础。

 realm.executeTransaction(new Realm.Transaction() { // must be in transaction for this to work
     @Override
     public void execute(Realm realm) {
         // increment index
         Number currentIdNum = realm.where(users.class).max(usersFields.ID);
         int nextId;
         if(currentIdNum == null) {
            nextId = 1;
         } else {
            nextId = currentIdNum.intValue() + 1;
         }
         users user = new users(); // unmanaged
         user.setId(nextId);
         //...
         realm.insertOrUpdate(user); // using insert API
     }
 }

答案 1 :(得分:10)

这是一个陈旧且已经回答的问题,但我想发布我使用过的另一个解决方案。 你可以这样做:

Realm realm = Realm.getDefaultInstance();
// Realm transaction
realm.executeTransactionAsync(new Realm.Transaction() { 
    @Override
     public void execute(Realm bgRealm) {
         // Get the current max id in the users table
         Number maxId = bgRealm.where(users.class).max("id");
         // If there are no rows, currentId is null, so the next id must be 1
         // If currentId is not null, increment it by 1
         int nextId = (maxId == null) ? 1 : maxId.intValue() + 1;
         // User object created with the new Primary key
         users user = bgRealm.createObject(users.class, nextId);
         // Now you can update your object with your data. The object will be
         // automatically saved in the database when the execute method ends
         // ...
         // ... 
    }
}

答案 2 :(得分:3)

嗯,@ PrimaryKey只表示该字段是一个键。但是在创建对象并将其复制到Realm时自己设置它。考虑使用UUID.random(),手动增加它。 (如评论回答):Realm Auto Increament field example

答案 3 :(得分:1)

有一个示例,该示例按顺序实现了主键id的自动递增:

https://raw.githubusercontent.com/505aaron/realm-migration-example/master/realm/sequencer.js

const sequencer = (realmInstance, schema, props) => new Promise((resolve, reject) => {
  let saved;

  try {
    realmInstance.write(() => {
      const obj = { ...props };

      if (typeof obj.id === 'undefined') {
        let seq = realmInstance.objects('Sequence').filtered(`name = "${schema}"`)[0];
        if (typeof seq === 'undefined') {
          seq = realmInstance.create('Sequence', { name: schema, value: 0 });
        }
        obj.id = seq.next();
      }
      saved = realmInstance.create(schema, obj, true);

      resolve({ ...saved });
    });
  } catch (e) {
    reject(e);
  }
});

export default sequencer;

答案 4 :(得分:0)

对于本机反应

...
// this is the part where you are saving the newItem
realm.write(() => {
    // handle the id
    let id: any = realm.objects(this.Schema).max("id");
    newItem.id = id === undefined ? 1 : id++;
    realm.create(this.Schema, newItem);
    resolve(newItem);
});

答案 5 :(得分:0)

在科特林

我的界面

fun getRegistroIdentity(): Int

我的方法

class RegistroOver(private val realm: Realm) : RegistroImplementation {

override fun getRegistroIdentity(): Int {
    val registro = realm.where(Registro::class.java).max("id")
    val result: Int
    result = if (registro == null) {
        1
    } else {
        registro.toInt() + 1
    }
    return result
}}

:)

答案 6 :(得分:0)

一个简短的答案可能是这样的:

    Person person = new Person();
    person.setName("UserName");

    realm.beginTransaction();

    Number newId = realm.where(Person.class).max("id");
    person.setId(newId.intValue()+1);

    realm.copyToRealm(person);
    realm.commitTransaction();

答案 7 :(得分:-3)

在我个人的情况下,我将id设置为Unix时间值。我知道不是增量而是独特的

(int) System.currentTimeMillis() / 1000;