5
votes

Is there something similar to this: @Insert(onConflict = OnConflictStrategy.REPLACE) as found in Room database that you can do in Objectbox. If not, how can you avoid saving duplicate entries in an objectbox entity? Thanks.

2

2 Answers

0
votes

in object box DataModel class, make the item anotation

@unique Public String userID;


private Box<User> userBox;
userBox = ObjectBox.get().boxFor(User.class);

//your inserted object 

if (!userBox.getAll().contains(insertedObject)){
                        leadBoxForLeadOpions.put(l);
                    }
0
votes

Replacing objects should be simple enough as setting the @id(assignable=true) annotation to the wanted id field. I have tested it in my android app via:

@Test
fun testAssignableIdsGetReplaced() {
    val myUser1 = User()
    myUser1.id = 1
    myUser1.nickname = "Original"
    var currentList = boxStore!!.boxFor(User::class.java).all
    assert(currentList.size == 0)
    boxStore!!.boxFor(User::class.java).put(myUser1)
    currentList = boxStore!!.boxFor(User::class.java).all
    assert(currentList.size == 1)
    assert(currentList.get(0).id == 1L)
    val newUser1 = User()
    newUser1.id = 1
    newUser1.nickname = "New"
    boxStore!!.boxFor(User::class.java).put(newUser1)
    currentList = boxStore!!.boxFor(User::class.java).all
    assert(currentList.size == 1)
    assert(currentList.get(0).id == 1L)
    assert(currentList.get(0).nickname == newUser1.nickname)
}

@Entity
class User() {
  @Id(assignable = true) var id: Long = 0
  lateinitvar nickname: String
}

But bare in mind that using ids assignable annotation may produce sideeffects: https://docs.objectbox.io/relations#updating-relations
https://docs.objectbox.io/advanced/object-ids#self-assigned-object-ids