Package io.objectbox

Class BoxStore

  • All Implemented Interfaces:
    java.io.Closeable, java.lang.AutoCloseable

    @ThreadSafe
    public class BoxStore
    extends java.lang.Object
    implements java.io.Closeable
    Represents an ObjectBox database and gives you Boxes to get and put Objects of a specific type (see boxFor(Class)).
    • Field Detail

      • context

        @Nullable
        public static java.lang.Object context
        On Android used for native library loading.
      • relinker

        @Nullable
        public static java.lang.Object relinker
      • JNI_VERSION

        public static final java.lang.String JNI_VERSION
        Change so ReLinker will update native library when using workaround loading.
        See Also:
        Constant Field Values
    • Method Detail

      • getDefault

        public static BoxStore getDefault()
        Convenience singleton instance which gets set up using BoxStoreBuilder.buildDefault().

        Note: for better testability, you can usually avoid singletons by storing a BoxStore instance in some application scope object and pass it along.

      • clearDefaultStore

        public static boolean clearDefaultStore()
        Clears the convenience instance.

        Note: This is usually not required (for testability, please see the comment of getDefault()).

        Returns:
        true if a default store was available before
      • getVersion

        public static java.lang.String getVersion()
        Gets the Version of ObjectBox Java.
      • getVersionNative

        public static java.lang.String getVersionNative()
        Gets the Version of ObjectBox Core.
      • testUnalignedMemoryAccess

        public static void testUnalignedMemoryAccess()
        Diagnostics: If this method crashes on a device, please send us the logcat output.
      • isObjectBrowserAvailable

        public static boolean isObjectBrowserAvailable()
      • isSyncAvailable

        public static boolean isSyncAvailable()
      • isSyncServerAvailable

        public static boolean isSyncServerAvailable()
      • finalize

        protected void finalize()
                         throws java.lang.Throwable
        Explicitly call close() instead to avoid expensive finalization.
        Overrides:
        finalize in class java.lang.Object
        Throws:
        java.lang.Throwable
      • getEntityTypeIdOrThrow

        @Internal
        public int getEntityTypeIdOrThrow​(java.lang.Class entityClass)
      • getAllEntityClasses

        public java.util.Collection<java.lang.Class> getAllEntityClasses()
      • beginReadTx

        @Internal
        public io.objectbox.Transaction beginReadTx()
        Internal, low level method: use runInReadTx(Runnable) instead. Begins a transaction for read access only. Note: there may be only one read transaction per thread.
      • isClosed

        public boolean isClosed()
      • close

        public void close()
        Closes the BoxStore and frees associated resources. This method is useful for unit tests; most real applications should open a BoxStore once and keep it open until the app dies.

        WARNING: This is a somewhat delicate thing to do if you have threads running that may potentially still use the BoxStore. This results in undefined behavior, including the possibility of crashing.

        Specified by:
        close in interface java.lang.AutoCloseable
        Specified by:
        close in interface java.io.Closeable
      • deleteAllFiles

        public boolean deleteAllFiles()
        Danger zone! This will delete all data (files) of this BoxStore! You must call close() before and read the docs of that method carefully!

        A safer alternative: use the static deleteAllFiles(File) method before opening the BoxStore.

        Returns:
        true if the directory 1) was deleted successfully OR 2) did not exist in the first place. Note: If false is returned, any number of files may have been deleted before the failure happened.
      • deleteAllFiles

        public static boolean deleteAllFiles​(java.io.File objectStoreDirectory)
        Danger zone! This will delete all files in the given directory!

        No BoxStore may be alive using the given directory.

        If you did not use a custom name with BoxStoreBuilder, you can pass "new File(BoxStoreBuilder.DEFAULT_NAME)".

        Parameters:
        objectStoreDirectory - directory to be deleted; this is the value you previously provided to BoxStoreBuilder.directory(File)
        Returns:
        true if the directory 1) was deleted successfully OR 2) did not exist in the first place. Note: If false is returned, any number of files may have been deleted before the failure happened.
        Throws:
        java.lang.IllegalStateException - if the given directory is still used by a open BoxStore.
      • deleteAllFiles

        public static boolean deleteAllFiles​(java.lang.Object androidContext,
                                             @Nullable
                                             java.lang.String customDbNameOrNull)
        Danger zone! This will delete all files in the given directory!

        No BoxStore may be alive using the given name.

        If you did not use a custom name with BoxStoreBuilder, you can pass "new File(BoxStoreBuilder.DEFAULT_NAME)".

        Parameters:
        androidContext - provide an Android Context like Application or Service
        customDbNameOrNull - use null for default name, or the name you previously provided to BoxStoreBuilder.name(String).
        Returns:
        true if the directory 1) was deleted successfully OR 2) did not exist in the first place. Note: If false is returned, any number of files may have been deleted before the failure happened.
        Throws:
        java.lang.IllegalStateException - if the given name is still used by a open BoxStore.
      • deleteAllFiles

        public static boolean deleteAllFiles​(@Nullable
                                             java.io.File baseDirectoryOrNull,
                                             @Nullable
                                             java.lang.String customDbNameOrNull)
        Danger zone! This will delete all files in the given directory!

        No BoxStore may be alive using the given directory.

        If you did not use a custom name with BoxStoreBuilder, you can pass "new File(BoxStoreBuilder.DEFAULT_NAME)".

        Parameters:
        baseDirectoryOrNull - use null for no base dir, or the value you previously provided to BoxStoreBuilder.baseDirectory(File)
        customDbNameOrNull - use null for default name, or the name you previously provided to BoxStoreBuilder.name(String).
        Returns:
        true if the directory 1) was deleted successfully OR 2) did not exist in the first place. Note: If false is returned, any number of files may have been deleted before the failure happened.
        Throws:
        java.lang.IllegalStateException - if the given directory (+name) is still used by a open BoxStore.
      • removeAllObjects

        public void removeAllObjects()
        Removes all objects from all boxes, e.g. deletes all database content. Internally reads the current schema, drops all database content, then restores the schema in a single transaction.
      • unregisterTransaction

        @Internal
        public void unregisterTransaction​(io.objectbox.Transaction transaction)
      • boxFor

        public <T> Box<T> boxFor​(java.lang.Class<T> entityClass)
        Returns a Box for the given type. Objects are put into (and get from) their individual Box.

        Creates a Box only once and then always returns the cached instance.

      • runInTx

        public void runInTx​(java.lang.Runnable runnable)
        Runs the given runnable inside a transaction.

        Efficiency notes: it is advised to run multiple puts in a transaction because each commit requires an expensive disk synchronization.

      • runInReadTx

        public void runInReadTx​(java.lang.Runnable runnable)
        Runs the given runnable inside a read(-only) transaction. Multiple read transactions can occur at the same time. This allows multiple read operations (gets) using a single consistent state of data. Also, for a high number of read operations (thousands, e.g. in loops), it is advised to run them in a single read transaction for efficiency reasons.
      • callInReadTxWithRetry

        @Experimental
        public <T> T callInReadTxWithRetry​(java.util.concurrent.Callable<T> callable,
                                           int attempts,
                                           int initialBackOffInMs,
                                           boolean logAndHeal)
        Calls callInReadTx(Callable) and retries in case a DbException is thrown. If the given amount of attempts is reached, the last DbException will be thrown. Experimental: API might change.
      • callInReadTx

        public <T> T callInReadTx​(java.util.concurrent.Callable<T> callable)
        Calls the given callable inside a read(-only) transaction. Multiple read transactions can occur at the same time. This allows multiple read operations (gets) using a single consistent state of data. Also, for a high number of read operations (thousands, e.g. in loops), it is advised to run them in a single read transaction for efficiency reasons. Note that an exception thrown by the given Callable will be wrapped in a RuntimeException, if the exception is not a RuntimeException itself.
      • callInTx

        public <R> R callInTx​(java.util.concurrent.Callable<R> callable)
                       throws java.lang.Exception
        Like runInTx(Runnable), but allows returning a value and throwing an exception.
        Throws:
        java.lang.Exception
      • callInTxNoException

        public <R> R callInTxNoException​(java.util.concurrent.Callable<R> callable)
        Like callInTx(Callable), but throws no Exception. Any Exception thrown in the Callable is wrapped in a RuntimeException.
      • runInTxAsync

        public void runInTxAsync​(java.lang.Runnable runnable,
                                 @Nullable
                                 TxCallback<java.lang.Void> callback)
        Runs the given Runnable as a transaction in a separate thread. Once the transaction completes the given callback is called (callback may be null).

        See also runInTx(Runnable).

      • callInTxAsync

        public <R> void callInTxAsync​(java.util.concurrent.Callable<R> callable,
                                      @Nullable
                                      TxCallback<R> callback)
        Runs the given Runnable as a transaction in a separate thread. Once the transaction completes the given callback is called (callback may be null).

        * See also callInTx(Callable).

      • diagnose

        public java.lang.String diagnose()
        Gives info that can be useful for debugging.
        Returns:
        String that is typically logged by the application.
      • cleanStaleReadTransactions

        public int cleanStaleReadTransactions()
      • closeThreadResources

        public void closeThreadResources()
        Call this method from a thread that is about to be shutdown or likely not to use ObjectBox anymore: it frees any cached resources tied to the calling thread (e.g. readers). This method calls Box.closeThreadResources() for all initiated boxes (boxFor(Class)).
      • subscribe

        public SubscriptionBuilder<java.lang.Class> subscribe()
        A DataObserver can be subscribed to data changes using the returned builder. The observer is supplied via SubscriptionBuilder.observer(DataObserver) and will be notified once a transaction is committed and will receive changes to any object class.

        Threading notes: All observers are notified from one separate thread (pooled). Observers are not notified in parallel. The notification order is the same as the subscription order, although this may not always be guaranteed in the future.

        Note that failed or aborted transaction do not trigger observers.

      • startObjectBrowser

        @Experimental
        @Nullable
        public java.lang.String startObjectBrowser()
      • startObjectBrowser

        @Experimental
        @Nullable
        public java.lang.String startObjectBrowser​(int port)
      • startObjectBrowser

        @Experimental
        @Nullable
        public java.lang.String startObjectBrowser​(java.lang.String urlToBindTo)
      • stopObjectBrowser

        @Experimental
        public boolean stopObjectBrowser()
      • getObjectBrowserPort

        @Experimental
        public int getObjectBrowserPort()
      • isObjectBrowserRunning

        public boolean isObjectBrowserRunning()
      • setDbExceptionListener

        public void setDbExceptionListener​(DbExceptionListener dbExceptionListener)
        The given listener will be called when an exception is thrown. This for example allows a central error handling, e.g. a special logging for DB related exceptions.
      • subscribe

        public <T> SubscriptionBuilder<java.lang.Class<T>> subscribe​(java.lang.Class<T> forClass)
        Like subscribe(), but wires the supplied @DataObserver only to the given object class for notifications.
      • internalScheduleThread

        @Internal
        public java.util.concurrent.Future internalScheduleThread​(java.lang.Runnable runnable)
      • internalThreadPool

        @Internal
        public java.util.concurrent.ExecutorService internalThreadPool()
      • isDebugRelations

        @Internal
        public boolean isDebugRelations()
      • internalQueryAttempts

        @Internal
        public int internalQueryAttempts()
      • internalFailedReadTxAttemptCallback

        @Internal
        public TxCallback internalFailedReadTxAttemptCallback()
      • getNativeStore

        public long getNativeStore()
        If you want to use the same ObjectBox store using the C API, e.g. via JNI, this gives the required pointer, which you have to pass on to obx_store_wrap(). The procedure is like this:
        1) you create a BoxStore on the Java side
        2) you call this method to get the native store pointer
        3) you pass the native store pointer to your native code (e.g. via JNI)
        4) your native code calls obx_store_wrap() with the native store pointer to get a OBX_store pointer
        5) Using the OBX_store pointer, you can use the C API. Note: Once you close() this BoxStore, do not use it from the C API.