Skip to main content

How do I delete an object in ObjectBox?

Answer: Use box.remove(id).

  • If an object with that ID exists, it will be deleted and the method returns true.
  • If no object exists with that ID, it returns false.
  • For deleting multiple objects efficiently, use removeMany() or an equivalent bulk operation.

Purpose​

The box.remove() method deletes a single object from the database based on its unique ID.
It is transactional and ensures that either the object is removed successfully or the operation has no effect.


Code Examples​

Java example

Box<User> userBox = store.boxFor(User.class);
long userIdToDelete = 1;

boolean wasRemoved = userBox.remove(userIdToDelete);

if (wasRemoved) {
System.out.println("Successfully removed user with ID " + userIdToDelete);
} else {
System.out.println("Could not find user with ID " + userIdToDelete + " to remove.");
}

Edge Cases & Pitfalls​

  • Non-existent ID: Returns false (does not throw an exception).
  • Invalid ID (0 or negative): Treated as non-existent, returns false.
  • Bulk deletes: Use removeMany() for performance when removing multiple IDs.
  • Remove by object reference: Some bindings allow remove(object) in addition to remove(id).
  • Transactions: Removing multiple objects can be wrapped in a single transaction for atomicity.

See Also​