How do I insert or update objects in ObjectBox?
Answer: Use box.put().
- If the object's ID is
0ornull, 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
- Kotlin
- Swift
- Dart
- Python
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);
Kotlin example
val userBox = store.boxFor(User::class.java)
// Insert
val newUser = User(name = "Bob")
val newId = userBox.put(newUser)
// Update
val existingUser = userBox[newId]
existingUser?.let {
it.name = "Bob Johnson"
userBox.put(it)
}
Swift example
do {
let userBox = store.box(for: User.self)
// Insert
let newUser = User(name: "Charlie")
let newId = try userBox.put(newUser)
// Update
if var existingUser = try userBox.get(newId) {
existingUser.name = "Charlie Brown"
try userBox.put(existingUser)
}
} catch {
print("An error occurred: \(error)")
}
Dart example
final userBox = store.box<User>();
// Insert
final newUser = User(name: 'David');
final newId = userBox.put(newUser);
// Update
final existingUser = userBox.get(newId);
if (existingUser != null) {
existingUser.name = 'David Copperfield';
userBox.put(existingUser);
}
Python example
user_box = store.box(User)
# Insert
new_user = User(name="Eve")
new_id = user_box.put(new_user)
# Update
existing_user = user_box.get(new_id)
if existing_user:
existing_user.name = "Eve Adams"
user_box.put(existing_user)
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
0ornull.
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
- box.get() – Fetching objects
- box.remove() – Deleting objects
- Transactions – Ensuring atomicity and consistency