### Install and Run Python Example Source: https://docs.objectbox.io/tutorial-demo-project.md Installs the ObjectBox Python package and runs the demo tasks app. Ensure ObjectBox version is 4.0.0 or higher. ```bash # Make sure to install objectbox >= 4.0.0 $ pip install --upgrade objectbox $ ls example ollama tasks vectorsearch-cities $ cd tasks $ python main.py Welcome to the ObjectBox tasks-list app example. Type help or ? for a list of commands. > ``` -------------------------------- ### Clone Python App Example Source: https://docs.objectbox.io/tutorial-demo-project.md Clone the ObjectBox Python examples repository. This provides a complete, runnable example for Python integration. ```bash git clone https://github.com/objectbox/objectbox-python.git cd objectbox-python ``` -------------------------------- ### Clone Android App Example Source: https://docs.objectbox.io/tutorial-demo-project.md Clone the ObjectBox examples repository for the Android app. This provides a complete, runnable example for integration. ```bash git clone https://github.com/objectbox/objectbox-examples.git cd objectbox-examples/android-app ``` -------------------------------- ### Start ObjectBox Admin (Java) Source: https://docs.objectbox.io/data-browser.md After creating the BoxStore, instantiate the Admin class with the store and call its start method, passing the Android context. Check the return value for success. ```java boxStore = MyObjectBox.builder().androidContext(this).build(); if (BuildConfig.DEBUG) { boolean started = new Admin(boxStore).start(this); Log.i("ObjectBoxAdmin", "Started: " + started); } ``` -------------------------------- ### Install langchain-objectbox Source: https://docs.objectbox.io/on-device-vector-search.md Install the ObjectBox integration package for LangChain. This package enables ObjectBox to be used as a local on-device vector store. ```bash pip install langchain-objectbox --upgrade ``` -------------------------------- ### Clone Android Kotlin App Example Source: https://docs.objectbox.io/tutorial-demo-project.md Clone the ObjectBox examples repository for the Android Kotlin app. This provides a complete, runnable example for integration. ```bash git clone https://github.com/objectbox/objectbox-examples.git cd objectbox-examples/android-app-kotlin ``` -------------------------------- ### Clone Dart App Example Source: https://docs.objectbox.io/tutorial-demo-project.md Clone the ObjectBox Dart examples repository. This provides a complete, runnable example for Flutter integration. ```bash git clone https://github.com/objectbox/objectbox-dart.git cd objectbox-dart/objectbox/examples/flutter/objectbox_demo ``` -------------------------------- ### Initialize ObjectBox Store in Flutter Source: https://docs.objectbox.io/getting-started.md Set up the ObjectBox store for Flutter applications. The `create` method handles directory setup and opening the store. Call `ObjectBox.create()` when your app starts. ```dart import 'package:path/path.dart' as p; import 'package:path_provider/path_provider.dart'; import 'objectbox.g.dart'; // created by `flutter pub run build_runner build` class ObjectBox { /// The Store of this app. late final Store store; ObjectBox._create(this.store) { // Add any additional setup code, e.g. build queries. } /// Create an instance of ObjectBox to use throughout the app. static Future create() async { final docsDir = await getApplicationDocumentsDirectory(); // Future openStore() {...} is defined in the generated objectbox.g.dart final store = await openStore(directory: p.join(docsDir.path, "obx-example")); return ObjectBox._create(store); } } ``` -------------------------------- ### Example Debug Output Source: https://docs.objectbox.io/queries.md This is an example of the log output you will see in your console or logcat when query parameter logging is enabled and a query is executed. ```text Parameters for query #2: (firstName ==(i) "Joe" AND age < 12) ``` -------------------------------- ### Ask a Question via Documentation Index Source: https://docs.objectbox.io/ann-vector-search Perform an HTTP GET request to the documentation index with 'ask' and optional 'goal' parameters to get a direct answer to a question and relevant excerpts. ```http GET https://docs.objectbox.io/on-device-vector-search.md?ask=&goal= ``` -------------------------------- ### Install ObjectBox Python Package Source: https://docs.objectbox.io/getting-started.md Install the stable version of the ObjectBox Python package from PyPI using pip. ```sh pip install --upgrade objectbox ``` -------------------------------- ### Initialize ObjectBox Store for JVM Source: https://docs.objectbox.io/getting-started.md Initialize the ObjectBox store for JVM applications. This example specifies a database name. Call `ObjectBox.init(context)` typically within your main method. ```java public class ObjectBox { private static BoxStore store; public static void init(Context context) { store = MyObjectBox.builder() .name("objectbox-notes-db") .build(); } public static BoxStore get() { return store; } } ``` -------------------------------- ### Start ObjectBox Admin (Flutter) Source: https://docs.objectbox.io/data-browser.md Check if Admin is available and create an Admin instance with the store. Keep a reference to the instance. Optionally, call the close method when done. ```dart if (Admin.isAvailable()) { // Keep a reference until no longer needed or manually closed. admin = Admin(store); } // (Optional) Close at some later point. admin.close(); ``` -------------------------------- ### Get Flow from Box or Query Subscription Source: https://docs.objectbox.io/kotlin-support.md Provides examples of how to obtain a Kotlin Flow from ObjectBox subscriptions for listening to changes in a Box or query results. ```kotlin // Listen to all changes to a Box val flow = store.subscribe(TestEntity::class.java).toFlow() // Get the latest query results on any changes to a Box val flow = box.query().subscribe().toFlow() ``` -------------------------------- ### Get Box Instance in Kotlin Source: https://docs.objectbox.io/kotlin-support.md Compares the regular way of getting a Box instance with the more concise approach using ObjectBox's Kotlin extension functions. ```kotlin // Regular: val box = store.boxFor(DataClassEntity::class.java) // With extension: val box: Box = store.boxFor() ``` -------------------------------- ### Ask a Question via HTTP GET Source: https://docs.objectbox.io/llms.txt Use this method to query the documentation index with a specific question and an optional broader goal. The response includes a direct answer and relevant excerpts. ```http GET https://docs.objectbox.io/kotlin-support.md?ask=&goal= ``` -------------------------------- ### ViewModel with ObjectBoxDataSource Source: https://docs.objectbox.io/android/paging-architecture-components.md Example of a ViewModel class that builds a paginated LiveData using ObjectBoxDataSource and LivePagedListBuilder. Assumes Paging library is set up and an ObjectBox query is built. ```java public class NotePagedViewModel extends ViewModel { private LiveData> noteLiveDataPaged; public LiveData> getNoteLiveDataPaged(Box notesBox) { if (noteLiveDataPaged == null) { // query all notes, sorted a-z by their text Query query = notesBox.query().order(Note_.text).build(); // build LiveData noteLiveDataPaged = new LivePagedListBuilder<>( new ObjectBoxDataSource.Factory<>(query), 20 /* page size */ ).build(); } return noteLiveDataPaged; } } ``` -------------------------------- ### Java @BaseEntity Superclass and Subclass Example Source: https://docs.objectbox.io/advanced/entity-inheritance.md Demonstrates defining a base abstract class with @BaseEntity and a concrete entity subclass in Java. The base class properties are persisted in the subclass. ```java // Superclass: @BaseEntity public abstract class Base { @Id long id; String baseString; public Base() { } public Base(long id, String baseString) { this.id = id; this.baseString = baseString; } } // Subclass: @Entity public class Sub extends Base { String subString; public Sub() { } public Sub(long id, String baseString, String subString) { super(id, baseString); this.subString = subString; } } ``` -------------------------------- ### Add ARMv7 and AArch64 Linux Dependencies Source: https://docs.objectbox.io/release-history.md Include specific dependencies for ARMv7 and AArch64 Linux devices to support Java applications on these architectures. The setup is otherwise identical to Java Desktop Apps. ```gradle implementation "io.objectbox:objectbox-linux-armv7:$objectboxVersion ``` ```gradle implementation "io.objectbox:objectbox-linux-arm64:$objectboxVersion ``` -------------------------------- ### Configure ObjectBox Gradle Plugin and Android Dependency Source: https://docs.objectbox.io/release-history.md Specify the ObjectBox Gradle plugin version and the ObjectBox Android dependency in your build.gradle file. This example shows how to set the plugin to a preview version. ```groovy buildscript { dependencies { classpath "io.objectbox:objectbox-gradle-plugin:3.0.0-alpha2" } } dependencies { // Artifacts with native code remain at 2.5.1. implementation "io.objectbox:objectbox-android:2.5.1" } ``` -------------------------------- ### Get Box Instance for Entities Source: https://docs.objectbox.io/getting-started.md Obtain a Box instance for specific entity types like User and Order. This is the entry point for interacting with data of a given type. ```java Box userBox = store.boxFor(User.class); Box orderBox = store.boxFor(Order.class); ``` ```kotlin val userBox = store.boxFor(User::class) val orderBox = store.boxFor(Order::class) ``` ```dart final userBox = store.box(); final orderBox = store.box(); ``` ```python user_box = store.box(User) order_box = store.box(Order) ``` -------------------------------- ### C++: Nearest Neighbor Search Source: https://docs.objectbox.io/on-device-vector-search.md This snippet demonstrates how to perform a nearest neighbor search using C++ with ObjectBox. It shows the setup for a query targeting vector data and retrieving results. ```C++ // Query vector std::vector madrid = {40.416775f, -3.703790f}; // Prepare a Query object to search for the 2 closest neighbors: auto query = box.query(City_.location.nearestNeighbors(madrid, 2)).build(); // Retrieve IDs auto results = query.findIdsWithScores(); for (const auto& result : results) { std::cout << "City ID: " << result.id << ", distance: " << result.score << std::endl; } // Retrieve objects auto results = query.findWithScores(); for (const auto& result : results) { std::cout << "City: " << result.object().name() << ", distance: " << result.score() << std::endl; } ``` -------------------------------- ### Add ObjectBox Native Libraries for Local Unit Tests Source: https://docs.objectbox.io/android/android-local-unit-tests.md Include these dependencies in your app's build.gradle file to enable ObjectBox functionality in local unit tests. This setup is primarily for ObjectBox versions 1.4 or older, or for manual dependency management. ```java dependencies { // Required -- JUnit 4 framework testImplementation("junit:junit:4.12") // Optional -- manually add native ObjectBox library to override auto-detection testImplementation("io.objectbox:objectbox-linux:$objectboxVersion") testImplementation("io.objectbox:objectbox-macos:$objectboxVersion") testImplementation("io.objectbox:objectbox-windows:$objectboxVersion") // Not added automatically: // Since 2.9.0 we also provide ARM support for the Linux library testImplementation("io.objectbox:objectbox-linux-arm64:$objectboxVersion") testImplementation("io.objectbox:objectbox-linux-armv7:$objectboxVersion") } ``` -------------------------------- ### Initialize ObjectBox Box for Notes (Java) Source: https://docs.objectbox.io/tutorial-demo-project.md Sets up the `notesBox` for `Note` objects within the `onCreate` method. Requires `ObjectBox.get()` to access the BoxStore. ```Java public void onCreate(Bundle savedInstanceState) { ... notesBox = ObjectBox.get().boxFor(Note.class); ... } ``` -------------------------------- ### Kotlin @BaseEntity Superclass and Subclass Example Source: https://docs.objectbox.io/advanced/entity-inheritance.md Illustrates defining a base abstract class with @BaseEntity and a concrete entity subclass in Kotlin. Note that Kotlin data classes do not support inheritance, so regular classes are used. ```kotlin // Note: Kotlin data classes do not support inheritance, // so this example uses regular Kotlin classes. // Superclass: @BaseEntity abstract class Base { @Id var id: Long = 0 var baseString: String? = null constructor() constructor(id: Long, baseString: String?) { this.id = id this.baseString = baseString } } // Subclass: @Entity class Sub : Base { var subString: String? = null constructor() constructor(id: Long, baseString: String?, subString: String?) : super(id, baseString) { this.subString = subString } } ``` -------------------------------- ### Kotlin Base Test Class for ObjectBox Source: https://docs.objectbox.io/android/android-local-unit-tests.md Provides a base class for Kotlin tests, managing ObjectBox store setup and cleanup. Ensures a clean database state before each test by deleting existing files. ```kotlin open class AbstractObjectBoxTest { private var _store: BoxStore? = null protected val store: BoxStore get() = _store!! @Before fun setUp() { // Delete any files in the test directory before each test to start with a clean database. BoxStore.deleteAllFiles(TEST_DIRECTORY) _store = MyObjectBox.builder() // Use a custom directory to store the database files in. .directory(TEST_DIRECTORY) // Optional: add debug flags for more detailed ObjectBox log output. .debugFlags(DebugFlags.LOG_QUERIES or DebugFlags.LOG_QUERY_PARAMETERS) .build() } @After fun tearDown() { _store?.close() _store = null BoxStore.deleteAllFiles(TEST_DIRECTORY) } companion object { private val TEST_DIRECTORY = File("objectbox-example/test-db") } } ``` -------------------------------- ### Kotlin: Nearest Neighbor Search Source: https://docs.objectbox.io/on-device-vector-search.md Utilize Kotlin for nearest neighbor searches, showing how to define query vectors and retrieve both IDs and full objects with their associated distances. Includes an example of combining vector search with string filtering. ```Kotlin val madrid = floatArrayOf(40.416775f, -3.703790f) // query vector // Prepare a Query object to search for the 2 closest neighbors: val query = box .query(City_.location.nearestNeighbors(madrid, 2)) .build() // Combine with other conditions as usual val query = box .query( City_.location.nearestNeighbors(madrid, 2) .and(City_.name.startsWith("B")) ) .build() // Retrieve IDs val results = query.findIdsWithScores() for (result in results) { println("City ID: ${result.id}, distance: ${result.score}") } // Retrieve objects val results = query.findWithScores() for (result in results) { println("City: ${result.get().id}, distance: ${result.score}") } ``` -------------------------------- ### Initialize ObjectBox Store and Box (Dart) Source: https://docs.objectbox.io/tutorial-demo-project.md Sets up the ObjectBox store and a box for `Note` objects. The `_create` constructor initializes the store and the box. ```Dart class ObjectBox { late final Store _store; late final Box _box; ObjectBox._create(this._store) { _noteBox = Box(_store); ... ``` -------------------------------- ### ObjectBox Admin Docker Help Command Source: https://docs.objectbox.io/data-browser.md Displays the usage and available options for the objectbox-admin.sh script. Use this to understand how to specify database directories and ports. ```bash $ objectbox-admin.sh --help usag e: objectbox-admin.sh [options] [] ( defaults to ./objectbox ) should contain an objectbox "data.mdb" file. Available (optional) options: [--port ] Mapped bind port to localhost (defaults to 8081) ``` -------------------------------- ### Download ObjectBox Database Library for Unit Tests Source: https://docs.objectbox.io/getting-started.md Download the latest ObjectBox database library for your system using a bash script. Append --sync for the ObjectBox Sync variant. ```bash bash <(curl -s https://raw.githubusercontent.com/objectbox/objectbox-dart/main/install.sh) ``` ```bash bash <(curl -s https://raw.githubusercontent.com/objectbox/objectbox-dart/main/install.sh) --sync ``` -------------------------------- ### Initialize ObjectBox Box for Notes (Kotlin) Source: https://docs.objectbox.io/tutorial-demo-project.md Initializes the `notesBox` for `Note` objects using `ObjectBox.boxStore`. This is typically done in the `onCreate` method. ```Kotlin public override fun onCreate(savedInstanceState: Bundle?) { ... notesBox = ObjectBox.boxStore.boxFor() ... } ``` -------------------------------- ### Get Objects from a Box Source: https://docs.objectbox.io/getting-started.md Retrieve objects from a box by their ID using `get`. Use `getAll` to fetch all objects in the box. Dart also supports `getMany` for retrieving multiple objects by IDs. ```java User user = userBox.get(userId); List users = userBox.getAll(); ``` ```kotlin val user = userBox[userId] val users = userBox.all ``` ```dart final user = userBox.get(userId); final users = userBox.getMany(userIds); final users = userBox.getAll(); ``` ```python user = user_box.get(user_id) users = user_box.get_all() ``` -------------------------------- ### Get Teachers of a Student (Kotlin) Source: https://docs.objectbox.io/relations.md Retrieves and iterates through the teachers associated with a specific student. ```kotlin val student = boxStore.boxFor(Student::class.java).get(studentId) for (teacher in student.teachers) { // Do something with each teacher. } ``` -------------------------------- ### Get Teachers of a Student (Java) Source: https://docs.objectbox.io/relations.md Retrieves and iterates through the teachers associated with a specific student. ```java Student student = boxStore.boxFor(Student.class).get(studentId); for (Teacher teacher : student.teachers) { // Do something with each teacher. } ``` -------------------------------- ### Get Teachers of a Student (Dart) Source: https://docs.objectbox.io/relations.md Retrieves and iterates through the teachers associated with a specific student using Dart. ```dart Student student = store.box().get(studentId); // you can use any List<> functions, for example: student.teachers.forEach((Teacher teacher) => ...); ``` -------------------------------- ### Get ToOne Relation in Dart Source: https://docs.objectbox.io/relations.md Retrieve the related customer object from an order by accessing the target property. ```dart final order = store.box().get(orderId); final customer = order.customer.target; ``` -------------------------------- ### Build Query with Extensions Source: https://docs.objectbox.io/kotlin-support.md Demonstrates how to build a query using ObjectBox's Kotlin extension functions for a more fluent API compared to the regular method. ```kotlin // Regular: val query = box.query().run { equal(property, value) order(property) build() } // With extension: val query = box.query { equal(property, value) order(property) } ``` -------------------------------- ### Get ToOne Relation in Kotlin Source: https://docs.objectbox.io/relations.md Retrieve the related customer object from an order by accessing the target property. ```kotlin val order = boxStore.boxFor(Order::class.java)[orderId] val customer = order.customer.target ``` -------------------------------- ### Get ToOne Relation in Java Source: https://docs.objectbox.io/relations.md Retrieve the related customer object from an order by calling getTarget() on the ToOne instance. ```java Order order = boxStore.boxFor(Order.class).get(orderId); Customer customer = order.customer.getTarget(); ``` -------------------------------- ### C++ Generated City Struct Source: https://docs.objectbox.io/on-device-vector-search.md Example of the generated City struct in C++ after running the ObjectBox Generator on the FlatBuffer schema. ```C++ struct City { obx_id id; std::string name; std::vector location; } ``` -------------------------------- ### Initialize ObjectBox Store and Box (Python) Source: https://docs.objectbox.io/tutorial-demo-project.md Initializes the ObjectBox store with a specified directory and creates a box for `Task` objects. This is part of the `TasklistCmd` class initialization. ```Python class TasklistCmd(Cmd): # ... def __init__(self): # ... self._store = Store(directory="tasklist-db") self._task_box = self._store.box(Task) ``` -------------------------------- ### Initialize ObjectBox Store in Java (Android) Source: https://docs.objectbox.io/getting-started.md Use this helper class to initialize the ObjectBox store. Call `ObjectBox.init(context)` in your Application class's onCreate method. ```java public class ObjectBox { private static BoxStore store; public static void init(Context context) { store = MyObjectBox.builder() .androidContext(context) .build(); } public static BoxStore get() { return store; } } ``` ```java public class ExampleApp extends Application { @Override public void onCreate() { super.onCreate(); ObjectBox.init(this); } } ``` -------------------------------- ### Get Entity UID in Python Source: https://docs.objectbox.io/advanced/data-model-updates.md In Python, retrieve the UID of an existing entity by accessing its internal _uid attribute before renaming. ```python @Entity() class MyName: id = Id some_property = Int print(MyName._uid) # 6645479796472661392 ``` -------------------------------- ### Get Customer Orders (1:N) Source: https://docs.objectbox.io/relations.md Retrieve a customer entity and iterate through its associated orders. This is useful for accessing related data after it has been persisted. ```java Customer customer = boxStore.boxFor(Customer.class).get(customerId); for (Order order : customer.orders) { // Do something with each order. } ``` ```kotlin val customer = boxStore.boxFor(Customer::class.java).get(customerId) for (order in customer.orders) { // Do something with each order. } ``` ```dart Customer customer = store.box().get(customerId); // you can use any List<> functions, for example: final valueSum = customer.orders.fold(0, (sum, order) => sum + order.value); // though you could use property queries and their .sum() function for that ``` -------------------------------- ### Download ObjectBox C Library with Sync for Dart Native Source: https://docs.objectbox.io/getting-started.md Download the ObjectBox C library with support for ObjectBox Sync. The script downloads the library into the 'lib' subdirectory by default. ```bash bash <(curl -s https://raw.githubusercontent.com/objectbox/objectbox-dart/main/install.sh) --sync ``` -------------------------------- ### Create ObjectBox Store in Python Source: https://docs.objectbox.io/getting-started.md Initialize a default ObjectBox store in Python. The store will be created in the current working directory. ```python from objectbox import Store store = Store() ``` -------------------------------- ### Assign Object IDs Automatically (Python) Source: https://docs.objectbox.io/getting-started.md Example of ObjectBox automatically assigning an ID to a User object in Python. The ID is assigned after the object is put. ```python user = User() box.put(user) id: int = user.id ``` -------------------------------- ### Download ObjectBox C Library for Dart Native Source: https://docs.objectbox.io/getting-started.md Download the ObjectBox C library for your system. The script downloads the library into the 'lib' subdirectory by default. ```bash bash <(curl -s https://raw.githubusercontent.com/objectbox/objectbox-dart/main/install.sh) ``` -------------------------------- ### Java @BaseEntity with Relations (Not Supported) Source: https://docs.objectbox.io/advanced/entity-inheritance.md Illustrates that superclasses annotated with @BaseEntity cannot have relations (like ToOne or ToMany properties) in Java. This code example will not work. ```java // THIS DOES NOT WORK @BaseEntity public abstract class Base { @Id long id; ToOne other; ToMany others; } ``` -------------------------------- ### Apply ObjectBox and Kapt Plugins (Root Gradle - Android) Source: https://docs.objectbox.io/getting-started.md Apply the kapt and ObjectBox plugins in the root Gradle build script for Android projects. ```kotlin plugins { alias(libs.plugins.android.application) apply false // Add the kapt plugin alias(libs.plugins.kotlin.kapt) apply false // Add the ObjectBox plugin alias(libs.plugins.objectbox) apply false } ``` -------------------------------- ### Describe Query Parameters in Dart Source: https://docs.objectbox.io/queries.md Use the describeParameters() method to get a string representation of the query's parameters in Dart. This can be printed to the console for debugging. ```dart print(query.describeParameters()); ``` -------------------------------- ### Kotlin @BaseEntity with Relations (Not Supported) Source: https://docs.objectbox.io/advanced/entity-inheritance.md Shows that superclasses annotated with @BaseEntity cannot contain relations (like ToOne or ToMany properties) in Kotlin. This code example is invalid. ```kotlin // THIS DOES NOT WORK @BaseEntity abstract class Base { @Id var id: Long = 0 lateinit var other: ToOne lateinit var others: ToMany } ``` -------------------------------- ### Execute Query and Update Adapter (Kotlin) Source: https://docs.objectbox.io/tutorial-demo-project.md Executes a previously built query to find all notes and updates the notes adapter with the results. ```kotlin val notes = notesQuery.find() notesAdapter.setNotes(notes) ``` -------------------------------- ### Create ObjectBox Vector Store with LangChain Source: https://docs.objectbox.io/on-device-vector-search.md Instantiate an ObjectBox vector store from texts and embeddings using LangChain. This is useful for setting up RAG with local data. ```python from langchain_objectbox.vectorstores import ObjectBox objectbox = ObjectBox.from_texts(texts, embeddings, embedding_dimensions=768) ``` -------------------------------- ### Stream Query Results as Objects in Flutter Source: https://docs.objectbox.io/data-observers-and-rx.md For Flutter apps, use .watch(triggerImmediately: true) and .map() to get a Stream of objects directly, suitable for StreamBuilder. ```dart // Build and watch the query, // set triggerImmediately to emit the query immediately on listen. return box.query(condition) .watch(triggerImmediately: true) // Map it to a list of objects to be used by a StreamBuilder. .map((query) => query.find()); ``` -------------------------------- ### Enable Query Parameter Logging in Java Source: https://docs.objectbox.io/queries.md Set the LOG_QUERY_PARAMETERS debug flag when building the BoxStore to log query parameters in Java. Execute a query afterwards to trigger the logging. ```java // Set the LOG_QUERY_PARAMETERS debug flag BoxStore store = MyObjectBox.builder() .debugFlags(DebugFlags.LOG_QUERY_PARAMETERS) .build(); // Execute a query query.find(); ``` -------------------------------- ### Get Rename UID from Build Error (Dart) Source: https://docs.objectbox.io/advanced/data-model-updates.md After adding an empty UID and building, ObjectBox provides the current UID for renaming in the error message for Dart. ```dart @Entity(uid: 0) found on "MyName" - you can choose one of the following actions: [Rename] apply the current UID using @Entity(uid: 6645479796472661392) [Change/reset] apply a new UID using @Entity(uid: 4385203238808477712) ``` -------------------------------- ### Run ObjectBox Admin Docker on Linux/macOS/WSL2 Source: https://docs.objectbox.io/data-browser.md Executes the ObjectBox Admin Docker image, mounting a local database directory and publishing the admin interface to port 8081. Replace /path/to/db with your actual database directory. ```shell docker run --rm -it --volume /path/to/db:/db -u $(id -u):$(id -g) --publish 8081:8081 objectboxio/admin:latest ``` -------------------------------- ### Get Rename UID from Build Error (Java/Kotlin) Source: https://docs.objectbox.io/advanced/data-model-updates.md After adding an empty UID and building, ObjectBox provides the current UID for renaming in the error message for Java/Kotlin. ```java error: [ObjectBox] UID operations for entity "MyName": [Rename] apply the current UID using @Uid(6645479796472661392L) - [Change/reset] apply a new UID using @Uid(4385203238808477712L) ``` -------------------------------- ### Execute Query and Update Adapter (Java) Source: https://docs.objectbox.io/tutorial-demo-project.md Executes a previously built query to find all notes and updates the notes adapter with the results. ```java List notes = notesQuery.find(); notesAdapter.setNotes(notes); ``` -------------------------------- ### Transform Query Results to Object Counts Source: https://docs.objectbox.io/data-observers-and-rx.md Transform data before it reaches the observer using the `transform()` method. This example transforms class objects into their stored object counts. ```java subscription = boxStore.subscribe() .transform(clazz -> return boxStore.boxFor(clazz).count()) .observer(count -> updateCount(count)); ``` -------------------------------- ### Create In-Memory ObjectBox Store in Python Source: https://docs.objectbox.io/getting-started.md Create an in-memory ObjectBox store in Python by prefixing the directory with 'memory:'. ```python store = Store(directory="memory:testdata") ``` -------------------------------- ### Manual ToOne/ToMany Initialization (Java) Source: https://docs.objectbox.io/relations.md Manually initialize ToOne and ToMany properties in Java entities when the ObjectBox Gradle plugin transformations are not supported. Requires a BoxStore field. ```java import io.objectbox.BoxStore; import io.objectbox.annotation.Entity; import io.objectbox.relation.ToMany; import io.objectbox.relation.ToOne; @Entity public class Example { ​ // Initialize ToOne and ToMany manually. ToOne order = new ToOne<>(this, Example_.order); ToMany orders = new ToMany<>(this, Example_.orders); // Add a BoxStore field. transient BoxStore __boxStore; } ``` -------------------------------- ### Count Objects in a Box Source: https://docs.objectbox.io/getting-started.md Get the total number of objects currently stored in a box. This provides a quick count of the data within a specific entity's box. ```java long userCount = userBox.count(); ``` ```kotlin val userCount = userBox.count() ``` ```dart final userCount = userBox.count(); ``` ```python user_box.count() ``` -------------------------------- ### Configure Repositories (settings.gradle.kts - Android) Source: https://docs.objectbox.io/getting-started.md Add Maven Central to the plugin and dependency repositories in the Gradle settings file for Android projects. ```kotlin pluginManagement { repositories { // Add Maven Central to the plugin repositories mavenCentral() } } dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) repositories { // Add Maven Central to the dependency repositories mavenCentral() } } ``` -------------------------------- ### Manual ToOne/ToMany Initialization (Kotlin) Source: https://docs.objectbox.io/relations.md Manually initialize ToOne and ToMany properties in Kotlin entities when the ObjectBox Gradle plugin transformations are not supported. Requires a BoxStore field and specific annotations. ```kotlin import io.objectbox.BoxStore; import io.objectbox.annotation.Entity; import io.objectbox.annotation.Id; import io.objectbox.relation.ToMany; import io.objectbox.relation.ToOne; @Entity class Example() { // Initialize ToOne and ToMany manually. var order = ToOne(this, Example_.order) var orders = ToMany(this, Example_.orders) // Add a BoxStore field. @JvmField @Transient @Suppress("PropertyName") var __boxStore: BoxStore? = null } ``` -------------------------------- ### Multiple Puts Triggering Separate Observer Notifications Source: https://docs.objectbox.io/data-observers-and-rx.md Individual box.put() or remove() calls start and commit implicit transactions, potentially triggering multiple observer notifications. ```java box.put(friendUser); box.put(myUser); // Log: // User friendUser put. // Observers of User called. // User myUser put. // Observers of User called. ``` -------------------------------- ### Dart/Flutter Entity with Flex Properties Source: https://docs.objectbox.io/property-types.md Define a Dart/Flutter entity with flex properties for dynamic types, string maps, or lists. Examples show setting string and integer tags. ```dart import 'package:objectbox/objectbox.dart'; @Entity() class Customer { @Id() int id = 0; // Stores any supported type at runtime dynamic tag; // Or explicitly use a String map (JSON-like) Map? stringMap; // Or a list with mixed types List? flexList; // Or a list of maps List>? nestedList; } // Example usage: // final customerStrTag = Customer()..tag = "string-tag"; // final customerIntTag = Customer()..tag = 1234; // box.putMany([customerStrTag, customerIntTag]); ``` -------------------------------- ### Build Query for Notes (Java) Source: https://docs.objectbox.io/tutorial-demo-project.md Builds a query to retrieve all notes, sorted alphabetically by their text. This query is typically built once and reused. ```java notesQuery = notesBox.query().order(Note_.text).build(); ``` -------------------------------- ### Build Query for Notes (Kotlin) Source: https://docs.objectbox.io/tutorial-demo-project.md Builds a query to retrieve all notes, sorted alphabetically by their text. This query is typically built once and reused. ```kotlin notesQuery = notesBox.query { order(Note_.text) } ``` -------------------------------- ### Example DB Schema Exception: Last Entity ID Mismatch Source: https://docs.objectbox.io/advanced/meta-model-ids-and-uids.md This exception occurs when the `lastEntityId` in the model file is incorrect and lower than the actual last entity ID in the database. ```java io.objectbox.exception.DbSchemaException: DB's last entity ID 4 is higher than 3 from model ``` -------------------------------- ### Define ObjectBox Version and Plugins (JVM) Source: https://docs.objectbox.io/getting-started.md Configure the TOML version catalog to define the ObjectBox version and aliases for the ObjectBox, Kotlin JVM, and Kapt plugins for JVM projects. ```toml [versions] # If using Kotlin kotlin = "KOTLIN_VERSION" # Define a variable for the version of the ObjectBox plugin objectbox = "OBJECTBOX_VERSION" [plugins] # If using Kotlin kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" } kotlin-kapt = { id = "org.jetbrains.kotlin.kapt", version.ref = "kotlin" } # Add an alias for the ObjectBox plugin objectbox = { id = "io.objectbox", version.ref = "objectbox" } ``` -------------------------------- ### Apply ObjectBox Plugin (Root Gradle - JVM) Source: https://docs.objectbox.io/getting-started.md Apply the ObjectBox plugin in the root Gradle build script for JVM projects. ```kotlin plugins { // If using Kotlin alias(libs.plugins.kotlin.jvm) apply false alias(libs.plugins.kotlin.kapt) apply false // Add the ObjectBox plugin alias(libs.plugins.objectbox) apply false } ``` -------------------------------- ### Kotlin Entity with Flex Properties Source: https://docs.objectbox.io/property-types.md Define a Kotlin data class with flex properties for dynamic types, string maps, or lists. Examples demonstrate storing string and integer tags. ```kotlin import io.objectbox.annotation.Entity import io.objectbox.annotation.Id @Entity data class Customer( @Id var id: Long = 0, // Stores any supported type at runtime var tag: Any? = null, // Or explicitly use a String map var stringMap: MutableMap? = null, // Or a list var flexList: MutableList? = null ) // Example usage: // val customerStrTag = Customer(tag = "string-tag") // val customerIntTag = Customer(tag = 1234) // box.put(customerStrTag, customerIntTag) ``` -------------------------------- ### Java Entity with Flex Properties Source: https://docs.objectbox.io/property-types.md Define a Java entity with flex properties to store dynamic types, string maps, or lists. Examples show storing string and integer tags. ```java import io.objectbox.annotation.Entity; import io.objectbox.annotation.Id; import javax.annotation.Nullable; import java.util.Map; import java.util.List; @Entity public class Customer { @Id long id; // Stores any supported type at runtime @Nullable Object tag; // Or explicitly use a String map @Nullable Map stringMap; // Or a list @Nullable List flexList; public Customer(Object tag) { this.id = 0; this.tag = tag; } public Customer() {} // For ObjectBox } // Example usage: // Customer customerStrTag = new Customer("string-tag"); // Customer customerIntTag = new Customer(1234); // box.put(customerStrTag, customerIntTag); ``` -------------------------------- ### Example DB Schema Exception: Entity UID Changed Source: https://docs.objectbox.io/advanced/meta-model-ids-and-uids.md This exception is thrown if the UID of an entity in the model file has been changed, causing a mismatch with the existing database's UID for that entity. ```java io.objectbox.exception.DbSchemaException: Incoming entity ID 1:6645479796472661392 does not match existing UID 8096888707432154961 ``` -------------------------------- ### Kotlin Inheriting from another Entity Example Source: https://docs.objectbox.io/advanced/entity-inheritance.md Demonstrates an entity class inheriting properties from another entity class in Kotlin. All properties from the superclass and its ancestors are included in the subclass's model. ```kotlin // Entities inherit properties from super entities. @Entity class SubSub : Sub { var subSubString: String? = null constructor() constructor(id: Long, baseString: String?, subString: String?, subSubString: String?) : super(id, baseString, subString) { this.subSubString= subSubString } } ``` -------------------------------- ### Create In-Memory Database Source: https://docs.objectbox.io/release-history.md Build a BoxStore for an in-memory database by calling the inMemory() method on the builder. This is useful for caching and testing. ```java store = MyObjectBox.builder() .androidContext(context) .inMemory("test-db") .build(); ``` -------------------------------- ### Java Inheriting from another Entity Example Source: https://docs.objectbox.io/advanced/entity-inheritance.md Shows how an entity class can inherit properties from another entity class in Java. The resulting model includes properties from all levels of the inheritance chain. ```java // Entities inherit properties from super entities. @Entity public class SubSub extends Sub { String subSubString; public SubSub() { } public SubSub(long id, String baseString, String subString, String subSubString) { super(id, baseString, subString); this.subSubString = subSubString; } } ``` -------------------------------- ### Initialize ObjectBox Store in Kotlin (Android) Source: https://docs.objectbox.io/getting-started.md This object provides a singleton instance for the ObjectBox store. Ensure `ObjectBox.init(this)` is called in your Application class's onCreate method. ```kotlin object ObjectBox { lateinit var store: BoxStore private set fun init(context: Context) { store = MyObjectBox.builder() .androidContext(context) .build() } } ``` ```kotlin class ExampleApp : Application() { override fun onCreate() { super.onCreate() ObjectBox.init(this) } } ``` -------------------------------- ### Java Local Unit Test with ObjectBox Source: https://docs.objectbox.io/android/android-local-unit-tests.md Implement a local unit test class in Java using ObjectBox. This snippet demonstrates setting up a test database in a custom directory, cleaning it before each test, and closing it afterward. ```java public class NoteTest { private static final File TEST_DIRECTORY = new File("objectbox-example/test-db"); private BoxStore store; @Before public void setUp() throws Exception { // Delete any files in the test directory before each test to start with a clean database. BoxStore.deleteAllFiles(TEST_DIRECTORY); store = MyObjectBox.builder() // Use a custom directory to store the database files in. .directory(TEST_DIRECTORY) // Optional: add debug flags for more detailed ObjectBox log output. .debugFlags(DebugFlags.LOG_QUERIES | DebugFlags.LOG_QUERY_PARAMETERS) .build(); } @After public void tearDown() throws Exception { if (store != null) { store.close(); store = null; } BoxStore.deleteAllFiles(TEST_DIRECTORY); } @Test public void exampleTest() { // get a box and use ObjectBox as usual Box noteBox = store.boxFor(Note.class); assertEquals(...); } } ``` -------------------------------- ### Python: AND with OR condition Source: https://docs.objectbox.io/queries.md Creates a query to find users whose first name is 'Joe' AND year of birth is greater than 1970, OR whose last name starts with 'O'. Note: 'one_of' is not available in Python. ```python query = userBox.query( (User.firstName.equals("Joe") & User.yearOfBirth.greater_than(1970)) | User.lastName.starts_with('O') ).build() joes = query.find() ``` -------------------------------- ### Add Platform-Specific Database Dependencies Source: https://docs.objectbox.io/getting-started.md Include ObjectBox database libraries for the platforms your application supports. Sync variants are also available. ```groovy dependencies { // ObjectBox platform-specific database libraries // Add or remove them as needed to match what your application supports. // There are Sync variants available named like "objectbox-sync-". // Linux (x64) implementation("io.objectbox:objectbox-linux:$objectboxVersion") // macOS (Intel and Apple Silicon) implementation("io.objectbox:objectbox-macos:$objectboxVersion") // Windows (x64) implementation("io.objectbox:objectbox-windows:$objectboxVersion") // Additional ObjectBox runtime libraries // Linux (32-bit ARM) implementation("io.objectbox:objectbox-linux-arm64:$objectboxVersion") // Linux (64-bit ARM) implementation("io.objectbox:objectbox-linux-armv7:$objectboxVersion") } ``` -------------------------------- ### Create ObjectBox Store in Dart (Native) Source: https://docs.objectbox.io/getting-started.md Open a store using the generated openStore() method. Remember to close the store when it's no longer needed. ```dart import 'objectbox.g.dart'; // created by `dart pub run build_runner build` void main() { // Store openStore() {...} is defined in the generated objectbox.g.dart final store = openStore(); // your app code ... store.close(); // don't forget to close the store } ``` -------------------------------- ### Apply ObjectBox and Kapt Plugins (App Gradle - Android) Source: https://docs.objectbox.io/getting-started.md Apply the kapt and ObjectBox plugins in the app's Gradle build script after the Android application plugin for Android projects. ```kotlin plugins { alias(libs.plugins.android.application) // Apply the kapt plugin alias(libs.plugins.kotlin.kapt) // Apply the ObjectBox plugin alias(libs.plugins.objectbox) } ``` -------------------------------- ### Define One-to-Many Relation with @Backlink in Java Source: https://docs.objectbox.io/relations.md Define a one-to-many relation by annotating the relation property with @Backlink, linking back to a to-one relation in the target object. This example shows a Customer having multiple Orders. ```java // Customer.java @Entity public class Customer { @Id public long id; @Backlink(to = "customer") public ToMany orders; } // Order.java @Entity public class Order { @Id public long id; public String name; public ToOne customer; public Order(String name) { this.name = name; } public Order() { } } ``` -------------------------------- ### Limit and Offset Query Results (Java) Source: https://docs.objectbox.io/queries.md Use `find(offset, limit)` to retrieve a specific range of results. The first `offset` results are skipped, and at most `limit` results are returned. ```java // offset by 10, limit to at most 5 results List joes = query.find(10, 5); ``` -------------------------------- ### Define Entity with Secondary String ID in Dart Source: https://docs.objectbox.io/entity-annotations.md Model entities with non-integer IDs as regular properties and index them. Use @Index() or @Unique() for efficient lookups. This example shows a string 'uid' property. ```dart @Entity() class StringIdEntity( int id; @Index() // or alternatively use @Unique() String uid; ) final objects = box.query(StringIdEntity_.uid.equals('...')).build().find(); ``` -------------------------------- ### Define ObjectBox Version and Plugins (Android) Source: https://docs.objectbox.io/getting-started.md Configure the TOML version catalog to define the ObjectBox version and aliases for the ObjectBox and kapt plugins for Android projects. ```toml [versions] agp = "AGP_VERSION" # Define a variable for the version of the ObjectBox plugin objectbox = "OBJECTBOX_VERSION" [plugins] android-application = { id = "com.android.application", version.ref = "agp" } # Add an alias for the kapt plugin kotlin-kapt = { id = "com.android.legacy-kapt", version.ref = "agp" } # Add an alias for the ObjectBox plugin objectbox = { id = "io.objectbox", version.ref = "objectbox" } ``` -------------------------------- ### Define Entity with Secondary String ID in Java Source: https://docs.objectbox.io/entity-annotations.md Model entities with non-integer IDs as regular properties and index them. Use @Index or @Unique for efficient lookups. This example shows a string 'uid' property. ```java @Entity class StringIdEntity { @Id public long id; @Index public String uid; // Alternatively: // @Unique String uid; } StringIdEntity entity = box.query() .equal(StringIdEntity_.uid, uid, StringOrder.CASE_SENSITIVE) .build().findUnique() ``` -------------------------------- ### Java Entity with Access Options Source: https://docs.objectbox.io/entity-annotations.md Demonstrates making entity fields accessible to ObjectBox by either not using private visibility or by providing standard getters. Includes default and all-properties constructors. ```java import javax.persistence.Entity; import javax.persistence.Id; @Entity public class Order { // Option 1: field is not private. @Id long id; // Option 2: field is private, but getter is available. private String name; public ToOne customer; public ToMany relatedOrders; // At minimum, provide a default constructor for ObjectBox. public Order() { } // Optional: all-properties constructor for better performance. // - make sure type matches exactly, // - for ToOne add its virtual ID property instead, // - for ToMany add no parameter. public Order(long id, String name, long customerId) { this.id = id; this.name = name; this.customer.setTargetId(customerId); } public String getName() { return this.name; } } ```