### Install Dart ObjectBox Sync Library Source: https://docs.objectbox.io/getting-started Downloads and installs the ObjectBox C library with support for ObjectBox Sync. This is an alternative installation for projects utilizing the Sync feature. ```bash bash <(curl -s https://raw.githubusercontent.com/objectbox/objectbox-dart/main/install.sh) --sync ``` -------------------------------- ### Clone ObjectBox Examples Repository Source: https://docs.objectbox.io/tutorial-demo-project Demonstrates how to clone the ObjectBox examples repository for different platforms (Android, Kotlin, Dart, Python) to explore the library's usage. This is the first step to running the provided demo applications. ```bash git clone https://github.com/objectbox/objectbox-examples.git cd objectbox-examples/android-app ``` ```bash git clone https://github.com/objectbox/objectbox-examples.git cd objectbox-examples/android-app-kotlin ``` ```bash git clone https://github.com/objectbox/objectbox-dart.git cd objectbox-dart/objectbox/examples/flutter/objectbox_demo ``` ```bash git clone https://github.com/objectbox/objectbox-python.git cd objectbox-python ``` -------------------------------- ### Java: Start ObjectBox Admin Source: https://docs.objectbox.io/data-browser Instantiate the `Admin` class with the `boxStore` and call `start` within a debug build check to launch the ObjectBox Admin interface. ```java boxStore = MyObjectBox.builder().androidContext(this).build(); if (BuildConfig.DEBUG) { boolean started = new Admin(boxStore).start(this); Log.i("ObjectBoxAdmin", "Started: " + started); } ``` -------------------------------- ### Install Dart ObjectBox Native Library Source: https://docs.objectbox.io/getting-started Downloads and installs the ObjectBox C library required for Dart native projects. This script fetches the library and places it in the `lib` subdirectory. ```bash bash <(curl -s https://raw.githubusercontent.com/objectbox/objectbox-dart/main/install.sh) ``` -------------------------------- ### Install langchain-objectbox Source: https://docs.objectbox.io/on-device-vector-search Installs the ObjectBox integration package for LangChain, enabling ObjectBox to be used as a local vector store within the LangChain framework. ```bash pip install langchain-objectbox --upgrade ``` -------------------------------- ### Install Python ObjectBox Package Source: https://docs.objectbox.io/getting-started Installs the ObjectBox library for Python projects using pip. This command ensures you have the latest stable version available on PyPI. ```sh pip install --upgrade objectbox ``` -------------------------------- ### Python Basic Store Initialization Source: https://docs.objectbox.io/getting-started A minimal example showing how to initialize an ObjectBox store in Python. By default, it creates a database file in the current working directory. ```python from objectbox import Store store = Store() ``` -------------------------------- ### Run Python ObjectBox Demo Source: https://docs.objectbox.io/tutorial-demo-project Provides instructions on how to navigate to the Python ObjectBox example directory and run the main application script. It also shows the initial output and command prompt. ```bash $ 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. > ``` -------------------------------- ### Initialize ObjectBox Box for Notes Source: https://docs.objectbox.io/tutorial-demo-project Demonstrates how to obtain a Box instance for the Note object, which is the primary interface for database operations. This setup is crucial before performing any data manipulation. ```Java notesBox = ObjectBox.get().boxFor(Note.class); ``` ```Kotlin notesBox = ObjectBox.boxStore.boxFor() ``` ```Dart _noteBox = Box(_store); ``` ```Python self._task_box = self._store.box(Task) ``` -------------------------------- ### Enable ObjectBox Plugin Debug Mode Source: https://docs.objectbox.io/advanced/advanced-setup Enable debug output for the ObjectBox Gradle plugin to help diagnose setup issues. This is configured separately from annotation processor arguments. ```groovy // Groovy DSL objectbox { debug = true } ``` ```kotlin // Kotlin DSL configure { debug.set(true) } ``` -------------------------------- ### Run ObjectBox Admin Script (Local DB) Source: https://docs.objectbox.io/data-browser Demonstrates executing the `objectbox-admin.sh` script from the directory where the ObjectBox database (`data.mdb`) is located. This is a common way to start the Admin tool for a local database. ```bash cd objectbox-c/examples/cpp-gen objectbox-admin.sh ``` -------------------------------- ### Install Dart ObjectBox Packages Source: https://docs.objectbox.io/getting-started Adds the ObjectBox SDK and build runner dependencies to your Dart project using `dart pub add`. This ensures your project has the necessary tools for ObjectBox integration. ```bash dart pub add objectbox dart pub add --dev build_runner objectbox_generator:any ``` -------------------------------- ### AbstractObjectBoxTest Setup (Java, Kotlin) Source: https://docs.objectbox.io/android/android-local-unit-tests Provides a base class for ObjectBox tests, handling the setup and teardown of the BoxStore. It ensures a clean database environment for each test by deleting existing files and configuring the store with a custom directory and debug flags. ```Java public class AbstractObjectBoxTest { private static final File TEST_DIRECTORY = new File("objectbox-example/test-db"); protected 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); } } ``` ```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") } } ``` -------------------------------- ### ObjectBox Flutter `pubspec.yaml` Dependencies Source: https://docs.objectbox.io/getting-started Example content for a Flutter project's `pubspec.yaml` file, specifying dependencies for ObjectBox, Flutter libraries, and development tools like `build_runner` and `objectbox_generator`. ```yaml dependencies: objectbox: ^4.3.0 objectbox_flutter_libs: any # If you run the command for ObjectBox Sync it should add instead: # objectbox_sync_flutter_libs: any dev_dependencies: build_runner: ^2.4.11 objectbox_generator: any ``` -------------------------------- ### ObjectBox Box Get Operations Source: https://docs.objectbox.io/getting-started Illustrates how to retrieve objects from an ObjectBox Box. The `get` method fetches a single object by its ID, while `getAll` retrieves all objects in the box. ```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() ``` -------------------------------- ### Manual ToOne/ToMany Initialization (Java) Source: https://docs.objectbox.io/relations Provides an example of manual initialization for `ToOne` and `ToMany` properties in Java when automatic transformations are not supported. This is necessary for Kotlin JVM projects on Linux, macOS, and Windows, requiring explicit instantiation and a `BoxStore` field. ```Java @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; } ``` -------------------------------- ### ObjectBox Gradle Dependencies Setup Source: https://docs.objectbox.io/getting-started Configures ObjectBox platform-specific runtime libraries and applies the ObjectBox Gradle plugin in a Gradle build script. This ensures the correct native libraries are included for your application's target platforms. ```groovy dependencies { // ObjectBox platform-specific runtime libraries // Add or remove them as needed to match what your application supports // 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") } // When manually adding ObjectBox dependencies, the plugin must be // applied after the dependencies block so it can detect them. // Using Groovy build scripts apply plugin: "io.objectbox" // Using KTS build scripts apply(plugin = "io.objectbox") ``` -------------------------------- ### Initialize ObjectBox Store (Kotlin Android) Source: https://docs.objectbox.io/getting-started Provides an example of initializing a BoxStore for Android using Kotlin. It uses an object for the helper class and the androidContext() builder method. The recommended place for initialization is the 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) } } ``` -------------------------------- ### Dart: Start ObjectBox Admin Source: https://docs.objectbox.io/data-browser Conditionally create an `Admin` instance with the `store` and keep a reference. The `Admin.isAvailable()` check ensures it's only attempted when possible. Optionally, the `admin` instance can be closed. ```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(); ``` -------------------------------- ### In-Memory Database Configuration Source: https://docs.objectbox.io/getting-started Examples for configuring ObjectBox to use an in-memory database, which is useful for testing or caching without creating persistent files. This is shown for Java, Dart, and Python. ```java BoxStore inMemoryStore = MyObjectBox.builder() .androidContext(context) .inMemory("test-db") .build(); ``` ```dart final inMemoryStore = Store(getObjectBoxModel(), directory: "memory:test-db"); ``` ```python store = Store(directory="memory:testdata") ``` -------------------------------- ### Get Box: Regular vs. Kotlin Extension Source: https://docs.objectbox.io/kotlin-support Demonstrates retrieving a Box for an entity using standard Kotlin syntax versus ObjectBox's Kotlin extension functions for conciseness. ```kotlin // Regular: val box = store.boxFor(DataClassEntity::class.java) ``` ```kotlin // With extension: val box: Box = store.boxFor() ``` -------------------------------- ### Get ObjectBox Box Instance Source: https://docs.objectbox.io/getting-started Demonstrates how to obtain a Box instance for specific entity types (e.g., User, Order) from an ObjectBox store. A Box provides access to objects of a particular 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) ``` -------------------------------- ### ObjectBox Gradle Plugin Configuration Source: https://docs.objectbox.io/release-history Example of how to configure the ObjectBox Gradle plugin to use a specific version, including the preview release for ObjectBox Java. ```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" } ``` -------------------------------- ### Configure ObjectBox Processor Options Source: https://docs.objectbox.io/advanced/advanced-setup Set ObjectBox annotation processor arguments to customize model path, package name, and debug mode. These options are applied differently based on the build system and language (Kotlin/Java) for Android and JVM projects. ```kotlin kapt { arguments { arg("objectbox.modelPath", "$projectDir/schemas/objectbox.json") arg("objectbox.myObjectBoxPackage", "com.example.custom") arg("objectbox.debug", true) } } ``` ```java // Groovy DSL (build.gradle) android { defaultConfig { javaCompileOptions { annotationProcessorOptions { arguments = [ "objectbox.modelPath" : "$projectDir/schemas/objectbox.json".toString(), "objectbox.myObjectBoxPackage" : "com.example.custom", "objectbox.debug" : "true" ] } } } } // Kotlin DSL (build.gradle.kts) android { defaultConfig { javaCompileOptions { annotationProcessorOptions { arguments.put("objectbox.modelPath", "$projectDir/schemas/objectbox.json") arguments.put("objectbox.myObjectBoxPackage", "com.example.custom") arguments.put("objectbox.debug", "true") } } } } ``` ```groovy // Groovy DSL tasks.withType(JavaCompile) { options.compilerArgs += [ "-Aobjectbox.modelPath=$projectDir/schemas/objectbox.json" ] options.compilerArgs += [ "-Aobjectbox.myObjectBoxPackage=com.example.custom" ] options.compilerArgs += [ "-Aobjectbox.debug=true" ] } ``` ```kotlin // Kotlin DSL tasks.withType() { options.compilerArgs.add("-Aobjectbox.modelPath=$projectDir/schemas/objectbox.json") options.compilerArgs.add("-Aobjectbox.myObjectBoxPackage=com.example.custom") options.compilerArgs.add("-Aobjectbox.debug=true") } ``` -------------------------------- ### Dart Flutter App Initialization Source: https://docs.objectbox.io/getting-started Initializes ObjectBox for a Flutter application and starts the app. Requires `WidgetsFlutterBinding.ensureInitialized()` for Flutter integration. ObjectBox instances are global per isolate, but native instances are shared across all isolates. ```dart late ObjectBox objectbox; Future main() async { // This is required so ObjectBox can get the application directory // to store the database in. WidgetsFlutterBinding.ensureInitialized(); objectbox = await ObjectBox.create(); runApp(MyApp()); } ``` -------------------------------- ### ObjectBox Maven Central Repository Setup Source: https://docs.objectbox.io/release-history Instructions for configuring Gradle to use the Sonatype OSSRH (Maven Central) repository for ObjectBox releases. This is essential for dependency management in build files. ```gradle repositories { mavenCentral() } ``` -------------------------------- ### ObjectBox OS Error Code Reference Source: https://docs.objectbox.io/troubleshooting Lists common OS error codes encountered with ObjectBox, providing their numeric value, errno name, and a brief description. This helps in diagnosing issues like attempting to initialize a database in a read-only location (e.g., error code 30). ```c Error Code | Errno | Description -------------------------------------------------- 1 | EPERM | Operation not permitted 2 | ENOENT | No such file or directory 3 | ESRCH | No such process 4 | EINTR | Interrupted system call 5 | EIO | I/O error 6 | ENXIO | No such device or address 7 | E2BIG | Argument list too long 8 | ENOEXEC | Exec format error 9 | EBADF | Bad file number 10 | ECHILD | No child processes 11 | EAGAIN | Try again 12 | ENOMEM | Out of memory 13 | EACCES | Permission denied 14 | EFAULT | Bad address 15 | ENOTBLK | Block device required 16 | EBUSY | Device or resource busy 17 | EEXIST | File exists 18 | EXDEV | Cross-device link 19 | ENODEV | No such device 20 | ENOTDIR | Not a directory 21 | EISDIR | Is a directory 22 | EINVAL | Invalid argument 23 | ENFILE | File table overflow 24 | EMFILE | Too many open files 25 | ENOTTY | Not a typewriter 26 | ETXTBSY | Text file busy 27 | EFBIG | File too large 28 | ENOSPC | No space left on device 29 | ESPIPE | Illegal seek 30 | EROFS | Read-only file system 31 | EMLINK | Too many links 32 | EPIPE | Broken pipe 33 | EDOM | Math argument out of domain of func 34 | ERANGE | Math result not representable ``` -------------------------------- ### Manage ObjectBox Data Subscriptions Source: https://docs.objectbox.io/data-observers-and-rx This example shows how to manage individual query subscriptions using a DataSubscription object. It covers keeping a reference to the subscription and explicitly calling cancel() when updates are no longer needed, such as when leaving a screen. ```java // Keep a reference for as long as updates should be received. DataSubscription subscription = boxStore.subscribe().observer(myObserver); // To no longer receive updates (e.g. leaving screen): subscription.cancel(); ``` -------------------------------- ### ObjectBox Data Model Migration Source: https://docs.objectbox.io/troubleshooting Guides users on resolving 'Incompatible property type' exceptions during ObjectBox data model updates. It directs users to the data model migration guide for detailed steps on handling property type changes. ```APIDOC ObjectBox Data Model Migration Guide: https://docs.objectbox.io/advanced/data-model-updates Common Exception: io.objectbox.exception.DbException: Property [...] is not compatible to its previous definition. Check its type. Cannot change the following flags for Property ``` -------------------------------- ### ObjectBox Admin Script Help Source: https://docs.objectbox.io/data-browser Displays the usage instructions and available options for the `objectbox-admin.sh` script. It outlines how to specify the database directory and map local ports for accessing the ObjectBox Admin interface. ```bash $ objectbox-admin.sh --help usage: 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) ``` -------------------------------- ### Query Notes Source: https://docs.objectbox.io/tutorial-demo-project Demonstrates how to build and execute queries to retrieve notes from ObjectBox. It covers ordering results by a specific field and executing the query to fetch data. ```Java notesQuery = notesBox.query().order(Note_.text).build(); List notes = notesQuery.find(); notesAdapter.setNotes(notes); ``` ```Kotlin notesQuery = notesBox.query { order(Note_.text) } val notes = notesQuery.find() notesAdapter.setNotes(notes) ``` ```Dart final builder = _noteBox.query().order(Note_.date, flags: Order.descending); return builder .watch(triggerImmediately: true) .map((query) => query.find()); ``` ```Python self._query = self._task_box.query().build() def find_tasks(self): return self._query.find() ``` -------------------------------- ### Initialize ObjectBox Store (JVM) Source: https://docs.objectbox.io/getting-started Shows how to create a BoxStore for JVM environments, typically for command-line applications. It uses the MyObjectBox builder and the name() method to specify the database directory. Initialization can be done within the 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; } } ``` -------------------------------- ### Get ToOne Relation Source: https://docs.objectbox.io/relations Shows how to retrieve the related target object from a `ToOne` relation. The target object is loaded lazily from the database upon first access. ```Java Order order = boxStore.boxFor(Order.class).get(orderId); Customer customer = order.customer.getTarget(); ``` ```Kotlin val order = boxStore.boxFor(Order::class.java)[orderId] val customer = order.customer.target ``` ```Dart final order = store.box().get(orderId); final customer = order.customer.target; ``` -------------------------------- ### Download ObjectBox Native Library for Unit Tests Source: https://docs.objectbox.io/getting-started A bash script to download the latest native ObjectBox library for local unit testing. This script can also be used with a `--sync` argument to fetch libraries supporting ObjectBox Sync. ```bash bash <(curl -s https://raw.githubusercontent.com/objectbox/objectbox-dart/main/install.sh) ``` -------------------------------- ### Object ID Assignment - Dart Source: https://docs.objectbox.io/getting-started Shows how ObjectBox assigns IDs to new objects in Dart. The ID is initially 0 and gets populated after the object is put into the box. ```Dart final user = User(); // user.id == 0 box.put(user); // user.id != 0 final id = user.id; ``` -------------------------------- ### Dart ObjectBox pubspec.yaml Configuration Source: https://docs.objectbox.io/getting-started Shows the expected additions to your `pubspec.yaml` file after running the `dart pub add` commands. This confirms the correct dependencies are listed. ```yaml dependencies: objectbox: ^4.3.0 dev_dependencies: build_runner: ^2.4.11 objectbox_generator: any ``` -------------------------------- ### Get Flow from Box/Query Subscription Source: https://docs.objectbox.io/kotlin-support Demonstrates how to obtain a Kotlin Flow from a Box or Query subscription, which is based on ObjectBox's Data Observer mechanism. ```kotlin // Listen to all changes to a Box val flow = store.subscribe(TestEntity::class.java).toFlow() ``` ```kotlin // Get the latest query results on any changes to a Box val flow = box.query().subscribe().toFlow() ``` -------------------------------- ### Dart Entity Property Accessibility Source: https://docs.objectbox.io/entity-annotations Illustrates Dart entity property accessibility, requiring non-private fields or getters/setters. Includes a constructor example. ```Dart @Entity() class User { int id; String? _name; String get name {...} set name(String value) {...} User(this.id); } ``` -------------------------------- ### ObjectBox Box Count Operation Source: https://docs.objectbox.io/getting-started Demonstrates how to get the total number of objects stored within an ObjectBox Box. This operation returns a count of all entities currently present in the box. ```Java long userCount = userBox.count(); ``` ```Kotlin val userCount = userBox.count() ``` ```Dart final userCount = userBox.count(); ``` ```Python user_box.count() ``` -------------------------------- ### Initialize ObjectBox Store (Java Android) Source: https://docs.objectbox.io/getting-started Demonstrates creating a BoxStore for Android applications using Java. It utilizes the generated MyObjectBox builder and the androidContext() method. Initialization is recommended in the 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); } } ``` -------------------------------- ### Kotlin Entity with Secondary String ID Source: https://docs.objectbox.io/entity-annotations Example of a Kotlin entity using a secondary string UID for lookups, indexed for performance. Demonstrates querying with the UID. ```Kotlin @Entity data class StringIdEntity( @Id var id: Long = 0, @Index var uid: String? = null // Alternatively: // @Unique uid: String? = null ) val entity = box.query( StringIdEntity_.uid, uid, StringOrder.CASE_SENSITIVE) .build().findUnique() ``` -------------------------------- ### ObjectBox Box Query Operations Source: https://docs.objectbox.io/getting-started Demonstrates how to build and execute queries to find objects matching specific criteria. Queries can include filtering, ordering, and building the query object for execution. ```Java Query query = userBox .query(User_.name.equal("Tom")) .order(User_.name) .build(); List results = query.find(); query.close(); ``` ```Kotlin val query = userBox .query(User_.name.equal("Tom")) .order(User_.name) .build() val results = query.find() query.close() ``` ```Dart final query = (userBox.query(User_.name.equals('Tom'))..order(User_.name)).build(); final results = query.find(); query.close(); ``` ```Python query = user_box \ .query(User.name.equals('Tom')) \ .build() results = query.find() ``` -------------------------------- ### Manually Add Libraries for Android Source: https://docs.objectbox.io/advanced/advanced-setup Provides the Gradle dependencies for manually adding ObjectBox libraries to an Android project. This includes the core Java library, Kotlin extensions, the annotation processor, and the native Android library. It also shows how to apply the ObjectBox Gradle plugin after the dependencies block to prevent overwrites. ```kotlin dependencies { // All below added automatically by the plugin: // Java library implementation("io.objectbox:objectbox-java:$objectboxVersion") // Kotlin extension functions implementation("io.objectbox:objectbox-kotlin:$objectboxVersion") // Annotation processor kapt("io.objectbox:objectbox-processor:$objectboxVersion") // Native library for Android implementation("io.objectbox:objectbox-android:$objectboxVersion") } // Apply plugin after dependencies block so they are not overwritten. apply plugin: 'io.objectbox' // Or using Kotlin DSL: apply(plugin = "io.objectbox") ``` ```java dependencies { // All below added automatically by the plugin: // Java library implementation("io.objectbox:objectbox-java:$objectboxVersion") // Annotation processor annotationProcessor("io.objectbox:objectbox-processor:$objectboxVersion") // Native library for Android implementation("io.objectbox:objectbox-android:$objectboxVersion") } // Apply plugin after dependencies block so they are not overwritten. apply plugin: 'io.objectbox' // Or using Kotlin DSL: apply(plugin = "io.objectbox") ``` -------------------------------- ### Manual ToOne/ToMany Initialization (Kotlin) Source: https://docs.objectbox.io/relations Illustrates manual initialization for `ToOne` and `ToMany` properties in Kotlin when automatic transformations are not supported. This requires explicit instantiation and a `BoxStore` field, along with specific annotations for the `BoxStore` field. ```Kotlin @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 } ``` -------------------------------- ### Configure ObjectBox Output Directory for Flutter/Dart Source: https://docs.objectbox.io/advanced/advanced-setup Customize the directory where ObjectBox generates model files and Dart code in a Flutter/Dart project. This is configured in the pubspec.yaml file. ```yaml objectbox: # Writes objectbox-model.json and objectbox.g.dart to lib/custom (and test/custom). output_dir: custom # Or optionally specify the lib and test output folder separately. # output_dir: # lib: custom # test: other ``` -------------------------------- ### Dart Native Store Creation and Management Source: https://docs.objectbox.io/getting-started Demonstrates creating an ObjectBox store using the generated `openStore()` method in a native Dart environment. It includes opening the store and properly closing it. ObjectBox instances are global per isolate, but native instances are shared across all isolates. ```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 } ``` -------------------------------- ### Dart Entity with Secondary String ID Source: https://docs.objectbox.io/entity-annotations Example of a Dart entity using a secondary string UID for lookups, indexed or unique. Shows how to query using the UID. ```Dart @Entity() class StringIdEntity( int id; @Index() // or alternatively use @Unique() String uid; ) final objects = box.query(StringIdEntity_.uid.equals('...')).build().find(); ``` -------------------------------- ### Manually Add Libraries for JVM Source: https://docs.objectbox.io/advanced/advanced-setup Details the Gradle dependencies for manually integrating ObjectBox into JVM projects. It lists the Java library, annotation processor, and various native libraries for different operating systems (Linux, macOS, Windows) and ARM architectures. This is crucial for distributing JVM apps that need to support multiple platforms. ```groovy dependencies { // All below added automatically by the plugin: // Java library implementation("io.objectbox:objectbox-java:$objectboxVersion") // Annotation processor annotationProcessor("io.objectbox:objectbox-processor:$objectboxVersion") // One of the native libraries required for your system implementation("io.objectbox:objectbox-linux:$objectboxVersion") implementation("io.objectbox:objectbox-macos:$objectboxVersion") implementation("io.objectbox:objectbox-windows:$objectboxVersion") // Not added automatically: // Since 2.9.0 we also provide ARM support for the Linux library implementation("io.objectbox:objectbox-linux-arm64:$objectboxVersion") implementation("io.objectbox:objectbox-linux-armv7:$objectboxVersion") } // Apply plugin after dependencies block so they are not overwritten. apply plugin: "io.objectbox" // Or using Kotlin DSL: apply(plugin = "io.objectbox") ``` ```kotlin dependencies { // All below added automatically by the plugin: // Java library implementation("io.objectbox:objectbox-java:$objectboxVersion") // Kotlin extension functions implementation("io.objectbox:objectbox-kotlin:$objectboxVersion") // Annotation processor kapt("io.objectbox:objectbox-processor:$objectboxVersion") // One of the native libraries required for your system implementation("io.objectbox:objectbox-linux:$objectboxVersion") implementation("io.objectbox:objectbox-macos:$objectboxVersion") implementation("io.objectbox:objectbox-windows:$objectboxVersion") // Not added automatically: // Since 2.9.0 we also provide ARM support for the Linux library implementation("io.objectbox:objectbox-linux-arm64:$objectboxVersion") implementation("io.objectbox:objectbox-linux-armv7:$objectboxVersion") } // Apply plugin after dependencies block so they are not overwritten. apply plugin: "io.objectbox" // Or using Kotlin DSL: apply(plugin = "io.objectbox") ``` -------------------------------- ### Configure Root build.gradle for ObjectBox (JVM) Source: https://docs.objectbox.io/getting-started Configures the root Gradle build file for JVM projects to include the ObjectBox Gradle plugin and define the ObjectBox version. It specifies repositories and dependencies for the build. ```groovy buildscript { ext.objectboxVersion = "4.3.0" // For Groovy build scripts // val objectboxVersion by extra("4.3.0") // For KTS build scripts repositories { mavenCentral() } dependencies { classpath("io.objectbox:objectbox-gradle-plugin:$objectboxVersion") } } ``` ```gradle.kts buildscript { // ext.objectboxVersion = "4.3.0" // For Groovy build scripts val objectboxVersion by extra("4.3.0") // For KTS build scripts repositories { mavenCentral() } dependencies { classpath("io.objectbox:objectbox-gradle-plugin:$objectboxVersion") } } ``` -------------------------------- ### Instantiate ObjectBox Vector Store with LangChain Source: https://docs.objectbox.io/on-device-vector-search Demonstrates how to initialize ObjectBox as a vector store using LangChain's `from_texts` method. This requires pre-existing text data and corresponding embeddings, along with the dimension of these embeddings. ```python from langchain_objectbox.vectorstores import ObjectBox # Assuming 'texts' is a list of strings and 'embeddings' is a list of embedding vectors # with a dimension of 768. objectbox = ObjectBox.from_texts(texts, embeddings, embedding_dimensions=768) ``` -------------------------------- ### Java Entity with Secondary String ID Source: https://docs.objectbox.io/entity-annotations Example of a Java entity using a secondary string UID for lookups, indexed for performance. It also shows how to query using this UID. ```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() ``` -------------------------------- ### Run ObjectBox Admin Docker (Linux/macOS/WSL2) Source: https://docs.objectbox.io/data-browser This command launches the ObjectBox Admin Docker image on Linux, macOS, or Windows Subsystem for Linux (WSL2). It mounts a local directory containing the ObjectBox database to the container and maps the container's port 8081 to the host's port 8081. It also includes user ID mapping for better permissions. ```shell docker run --rm -it --volume /path/to/db:/db -u $(id -u):$(id -g) --publish 8081:8081 objectboxio/admin:latest ``` -------------------------------- ### Java/Kotlin Explicit Write Transaction Example Source: https://docs.objectbox.io/transactions Demonstrates how to perform multiple ObjectBox operations within a single explicit write transaction in Java or Kotlin. This ensures atomicity for a series of data modifications. ```Java boxStore.runInTx(() -> { for(User user: allUsers) { if(modify(user)) box.put(user); else box.remove(user); } }); ``` ```Kotlin boxStore.runInTx { allUsers.forEach { if (modify(it)) box.put(it) else box.remove(it) } } ``` -------------------------------- ### Build Query: Regular vs. Kotlin Extension Source: https://docs.objectbox.io/kotlin-support Compares building a query using standard Kotlin methods versus the more fluent ObjectBox Kotlin extension functions. ```kotlin // Regular: val query = box.query().run { equal(property, value) order(property) build() } ``` ```kotlin // With extension: val query = box.query { equal(property, value) order(property) } ``` -------------------------------- ### Configure Root build.gradle for ObjectBox (Android) Source: https://docs.objectbox.io/getting-started Sets the ObjectBox version and applies the ObjectBox Gradle plugin in the root project's build.gradle file for Android. It configures repositories and dependencies required for the build process. ```groovy buildscript { ext.objectboxVersion = "4.3.0" // For Groovy build scripts // val objectboxVersion by extra("4.3.0") // For KTS build scripts repositories { mavenCentral() } dependencies { // Android Gradle Plugin 8.0 or later supported classpath("com.android.tools.build:gradle:8.0.2") classpath("io.objectbox:objectbox-gradle-plugin:$objectboxVersion") } } ``` ```gradle.kts buildscript { // ext.objectboxVersion = "4.3.0" // For Groovy build scripts val objectboxVersion by extra("4.3.0") // For KTS build scripts repositories { mavenCentral() } dependencies { // Android Gradle Plugin 8.0 or later supported classpath("com.android.tools.build:gradle:8.0.2") classpath("io.objectbox:objectbox-gradle-plugin:$objectboxVersion") } } ```