Skip to main content

How do I insert or update objects in ObjectBox?

Answer: Use box.put().

  • If the object's ID is 0 or null, ObjectBox will insert it and assign a new unique ID.
  • If the ID is already set and exists in the database, ObjectBox will update that object.
  • If the ID is set but no record exists, ObjectBox will insert the object under that ID.

This operation is transactional. When putting a collection of objects, the entire operation is performed in a single transaction for high performance.


Purpose

The box.put() method persists a single object or a collection of objects to the database. It handles both inserts and updates automatically.


Code Examples

Java example

// Insert or update a user
Box<User> userBox = store.boxFor(User.class);

// Insert: ID = 0 → new object
User newUser = new User("Alice");
long newId = userBox.put(newUser);

// Update: fetch, modify, and put again
User existingUser = userBox.get(newId);
existingUser.setName("Alice Smith");
userBox.put(existingUser);

Edge Cases & Pitfalls

  • Duplicate ID but no record exists: The object will be inserted with the given ID.
  • Null object: Calling put(null) will raise an error.
  • Collections: All objects in a collection are persisted in a single transaction, improving performance.
  • Concurrency: box.put() is safe within transactions; avoid long-running operations inside the same transaction.
  • Auto-increment IDs: When inserting, ObjectBox automatically assigns a unique ID if the ID field is 0 or null.
IDs 101

By default, ObjectBox assigns IDs when id == 0.
If you need to set IDs yourself, mark the ID as assignable in your binding (e.g., @Id(assignable = true) in Java/Kotlin).


See Also