io.objectbox.Box Java Examples

The following examples show how to use io.objectbox.Box. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: IndexReaderRenewTest.java    From objectbox-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testOldReaderWithIndex() {
    final Box<EntityLongIndex> box = store.boxFor(EntityLongIndex.class);
    final int initialValue = 1;

    final Query<EntityLongIndex> query = box.query().equal(EntityLongIndex_.indexedLong, 0).build();
    assertNull(query.findUnique());
    System.out.println("BEFORE put: " + box.getReaderDebugInfo());
    System.out.println("count before: " + box.count());

    box.put(createEntityLongIndex(initialValue));

    System.out.println("AFTER put: " + box.getReaderDebugInfo());
    System.out.println("count after: " + box.count());

    query.setParameter(EntityLongIndex_.indexedLong, initialValue);
    assertNotNull(query.findUnique());

    query.setParameter(EntityLongIndex_.indexedLong, 0);
    assertNull(query.findUnique());
}
 
Example #2
Source File: QueryTest.java    From objectbox-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testDateParam() {
    store.close();
    assertTrue(store.deleteAllFiles());
    store = MyObjectBox.builder().baseDirectory(boxStoreDir).debugFlags(DebugFlags.LOG_QUERY_PARAMETERS).build();

    Date now = new Date();
    Order order = new Order();
    order.setDate(now);
    Box<Order> box = store.boxFor(Order.class);
    box.put(order);

    Query<Order> query = box.query().equal(Order_.date, 0).build();
    assertEquals(0, query.count());

    query.setParameter(Order_.date, now);
}
 
Example #3
Source File: LazyList.java    From objectbox-java with Apache License 2.0 6 votes vote down vote up
LazyList(Box<E> box, long[] objectIds, boolean cacheEntities) {
    if (box == null || objectIds == null) {
        throw new NullPointerException("Illegal null parameters passed");
    }
    this.box = box;
    this.objectIds = objectIds;
    size = objectIds.length;
    if (cacheEntities) {
        entities = new ArrayList<>(size);
        for (int i = 0; i < size; i++) {
            entities.add(null);
        }
    } else {
        entities = null;
    }
}
 
Example #4
Source File: ObjectBoxDB.java    From Hentoid with Apache License 2.0 5 votes vote down vote up
void updateImageFileUrl(@NonNull final ImageFile image) {
    Box<ImageFile> imgBox = store.boxFor(ImageFile.class);
    ImageFile img = imgBox.get(image.getId());
    if (img != null) {
        img.setUrl(image.getUrl());
        imgBox.put(img);
    }
}
 
Example #5
Source File: ObjectBoxDB.java    From Hentoid with Apache License 2.0 5 votes vote down vote up
void updateImageFileStatusParamsMimeTypeUriSize(@NonNull ImageFile image) {
    Box<ImageFile> imgBox = store.boxFor(ImageFile.class);
    ImageFile img = imgBox.get(image.getId());
    if (img != null) {
        img.setStatus(image.getStatus());
        img.setDownloadParams(image.getDownloadParams());
        img.setMimeType(image.getMimeType());
        img.setFileUri(image.getFileUri());
        img.setSize(image.getSize());
        imgBox.put(img);
    }
}
 
Example #6
Source File: ObjectBoxDB.java    From Hentoid with Apache License 2.0 5 votes vote down vote up
/**
 * Remove the given content and all related objects from the DB
 * NB : ObjectBox v2.3.1 does not support cascade delete, so everything has to be done manually
 *
 * @param contentId IDs of the contents to be removed from the DB
 */
void deleteContentById(long[] contentId) {
    Box<ErrorRecord> errorBox = store.boxFor(ErrorRecord.class);
    Box<ImageFile> imageFileBox = store.boxFor(ImageFile.class);
    Box<Attribute> attributeBox = store.boxFor(Attribute.class);
    Box<AttributeLocation> locationBox = store.boxFor(AttributeLocation.class);
    Box<Content> contentBox = store.boxFor(Content.class);

    for (long id : contentId) {
        Content c = contentBox.get(id);
        if (c != null) {
            store.runInTx(() -> {
                if (c.getImageFiles() != null) {
                    for (ImageFile i : c.getImageFiles())
                        imageFileBox.remove(i);   // Delete imageFiles
                    c.getImageFiles().clear();                                      // Clear links to all imageFiles
                }

                if (c.getErrorLog() != null) {
                    for (ErrorRecord e : c.getErrorLog())
                        errorBox.remove(e);   // Delete error records
                    c.getErrorLog().clear();                                    // Clear links to all errorRecords
                }

                // Delete attribute when current content is the only content left on the attribute
                for (Attribute a : c.getAttributes())
                    if (1 == a.contents.size()) {
                        for (AttributeLocation l : a.getLocations())
                            locationBox.remove(l); // Delete all locations
                        a.getLocations().clear();                                           // Clear location links
                        attributeBox.remove(a);                                             // Delete the attribute itself
                    }
                c.getAttributes().clear();                                      // Clear links to all attributes

                contentBox.remove(c);                                           // Remove the content itself
            });
        }
    }
}
 
Example #7
Source File: ObjectBoxDB.java    From Hentoid with Apache License 2.0 5 votes vote down vote up
long insertContent(Content content) {
    List<Attribute> attributes = content.getAttributes();
    Box<Attribute> attrBox = store.boxFor(Attribute.class);
    Query attrByUniqueKey = attrBox.query().equal(Attribute_.type, 0).equal(Attribute_.name, "").build();

    return store.callInTxNoException(() -> {
        // Master data management managed manually
        // Ensure all known attributes are replaced by their ID before being inserted
        // Watch https://github.com/objectbox/objectbox-java/issues/509 for a lighter solution based on @Unique annotation
        Attribute dbAttr;
        Attribute inputAttr;
        if (attributes != null)
            for (int i = 0; i < attributes.size(); i++) {
                inputAttr = attributes.get(i);
                dbAttr = (Attribute) attrByUniqueKey.setParameter(Attribute_.name, inputAttr.getName())
                        .setParameter(Attribute_.type, inputAttr.getType().getCode())
                        .findFirst();
                if (dbAttr != null) {
                    attributes.set(i, dbAttr); // If existing -> set the existing attribute
                    dbAttr.addLocationsFrom(inputAttr);
                    attrBox.put(dbAttr);
                } else {
                    inputAttr.setName(inputAttr.getName().toLowerCase().trim()); // If new -> normalize the attribute
                }
            }

        return store.boxFor(Content.class).put(content);
    });
}
 
Example #8
Source File: QueryBuilder.java    From objectbox-java with Apache License 2.0 5 votes vote down vote up
@Internal
public QueryBuilder(Box<T> box, long storeHandle, String entityName) {
    this.box = box;
    this.storeHandle = storeHandle;
    handle = nativeCreate(storeHandle, entityName);
    isSubQuery = false;
}
 
Example #9
Source File: Query.java    From objectbox-java with Apache License 2.0 5 votes vote down vote up
Query(Box<T> box, long queryHandle, @Nullable List<EagerRelation<T, ?>> eagerRelations, @Nullable  QueryFilter<T> filter,
      @Nullable Comparator<T> comparator) {
    this.box = box;
    store = box.getStore();
    queryAttempts = store.internalQueryAttempts();
    handle = queryHandle;
    publisher = new QueryPublisher<>(this, box);
    this.eagerRelations = eagerRelations;
    this.filter = filter;
    this.comparator = comparator;
}
 
Example #10
Source File: QueryPublisher.java    From objectbox-java with Apache License 2.0 4 votes vote down vote up
QueryPublisher(Query<T> query, Box<T> box) {
    this.query = query;
    this.box = box;
}
 
Example #11
Source File: MockQuery.java    From objectbox-java with Apache License 2.0 4 votes vote down vote up
public Box<T> getBox() {
    return box;
}
 
Example #12
Source File: MockQuery.java    From ObjectBoxRxJava with Apache License 2.0 4 votes vote down vote up
public Box getBox() {
    return box;
}
 
Example #13
Source File: IndexReaderRenewTest.java    From objectbox-java with Apache License 2.0 4 votes vote down vote up
@Test
public void testOverwriteIndexedValue() throws InterruptedException {
    final Box<EntityLongIndex> box = store.boxFor(EntityLongIndex.class);
    final int initialValue = 1;

    final EntityLongIndex[] transformResults = {null, null, null};
    final CountDownLatch transformLatch1 = new CountDownLatch(1);
    final CountDownLatch transformLatch2 = new CountDownLatch(1);
    final AtomicInteger transformerCallCount = new AtomicInteger();

    final Query<EntityLongIndex> query = box.query().equal(EntityLongIndex_.indexedLong, 0).build();
    store.subscribe(EntityLongIndex.class).transform(javaClass -> {
        int callCount = transformerCallCount.incrementAndGet();
        if (callCount == 1) {
            query.setParameter(EntityLongIndex_.indexedLong, 1);
            EntityLongIndex unique = query.findUnique();
            transformLatch1.countDown();
            return unique;
        } else if (callCount == 2) {
            query.setParameter(EntityLongIndex_.indexedLong, 1);
            transformResults[0] = query.findUnique();
            transformResults[1] = query.findUnique();
            query.setParameter(EntityLongIndex_.indexedLong, 0);
            transformResults[2] = query.findUnique();
            transformLatch2.countDown();
            return transformResults[0];
        } else {
            throw new RuntimeException("Unexpected: " + callCount);
        }
    }).observer(data -> {
        // Dummy
    });

    assertTrue(transformLatch1.await(5, TimeUnit.SECONDS));
    box.put(createEntityLongIndex(initialValue));

    assertTrue(transformLatch2.await(5, TimeUnit.SECONDS));
    assertEquals(2, transformerCallCount.intValue());

    assertNotNull(transformResults[0]);
    assertNotNull(transformResults[1]);
    assertNull(transformResults[2]);

    query.setParameter(EntityLongIndex_.indexedLong, initialValue);
    assertNotNull(query.findUnique());

    query.setParameter(EntityLongIndex_.indexedLong, initialValue);
    assertNotNull(query.findUnique());
    assertNotNull(query.findUnique());
}
 
Example #14
Source File: IndexReaderRenewTest.java    From objectbox-java with Apache License 2.0 4 votes vote down vote up
@Test
public void testOldReaderInThread() throws InterruptedException {
    final Box<EntityLongIndex> box = store.boxFor(EntityLongIndex.class);
    final int initialValue = 1;

    final EntityLongIndex[] results = new EntityLongIndex[5];
    final CountDownLatch latchRead1 = new CountDownLatch(1);
    final CountDownLatch latchPut = new CountDownLatch(1);
    final CountDownLatch latchRead2 = new CountDownLatch(1);
    final Query<EntityLongIndex> query = box.query().equal(EntityLongIndex_.indexedLong, 0).build();

    new Thread(() -> {
        query.setParameter(EntityLongIndex_.indexedLong, initialValue);
        EntityLongIndex unique = query.findUnique();
        assertNull(unique);
        latchRead1.countDown();
        System.out.println("BEFORE put: " + box.getReaderDebugInfo());
        System.out.println("count before: " + box.count());

        try {
            latchPut.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        System.out.println("AFTER put: " + box.getReaderDebugInfo());
        System.out.println("count after: " + box.count());

        query.setParameter(EntityLongIndex_.indexedLong, initialValue);
        results[0] = query.findUnique();
        results[1] = box.get(1);
        results[2] = query.findUnique();
        query.setParameter(EntityLongIndex_.indexedLong, 0);
        results[3] = query.findUnique();
        latchRead2.countDown();
        box.closeThreadResources();
    }).start();

    assertTrue(latchRead1.await(5, TimeUnit.SECONDS));
    box.put(createEntityLongIndex(initialValue));
    latchPut.countDown();

    assertTrue(latchRead2.await(5, TimeUnit.SECONDS));

    assertNotNull(results[1]);
    assertNotNull(results[0]);
    assertNotNull(results[2]);
    assertNull(results[3]);

    query.setParameter(EntityLongIndex_.indexedLong, initialValue);
    assertNotNull(query.findUnique());

    query.setParameter(EntityLongIndex_.indexedLong, initialValue);
    assertNotNull(query.findUnique());
    assertNotNull(query.findUnique());
}
 
Example #15
Source File: ObjectBoxModule.java    From Building-Professional-Android-Applications with MIT License 4 votes vote down vote up
@Provides
@Named("stockPortfolioItem")
@Singleton
Box<StockPortfolioItem> providePortfolioRepository(BoxStore boxStore) {
    return boxStore.boxFor(StockPortfolioItem.class);
}
 
Example #16
Source File: MockQuery.java    From objectbox-java with Apache License 2.0 4 votes vote down vote up
public Box getBox() {
    return box;
}
 
Example #17
Source File: ProfileDialog.java    From andela-crypto-app with Apache License 2.0 4 votes vote down vote up
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Box<User> userBox = ((AndelaTrackChallenge) getActivity().getApplicationContext()).getBoxStore().boxFor(User.class);
    user = userBox.query().build().findFirst();
}
 
Example #18
Source File: ObjectBoxDB.java    From Hentoid with Apache License 2.0 4 votes vote down vote up
void updateQueue(@NonNull final List<QueueRecord> queue) {
    Box<QueueRecord> queueRecordBox = store.boxFor(QueueRecord.class);
    queueRecordBox.put(queue);
}
 
Example #19
Source File: ObjectBoxDB.java    From Hentoid with Apache License 2.0 4 votes vote down vote up
private void deleteQueue(long contentId) {
    Box<QueueRecord> queueRecordBox = store.boxFor(QueueRecord.class);
    QueueRecord record = queueRecordBox.query().equal(QueueRecord_.contentId, contentId).build().findFirst();

    if (record != null) queueRecordBox.remove(record);
}
 
Example #20
Source File: DbUtil.java    From weather with Apache License 2.0 2 votes vote down vote up
/**
 * Get query of multipleDaysWeatherBox
 *
 * @param multipleDaysWeatherBox instance of {@link Box<MultipleDaysWeather>}
 * @return instance of {@link Query<MultipleDaysWeather>}
 */
public static Query<MultipleDaysWeather> getMultipleDaysWeatherQuery(Box<MultipleDaysWeather> multipleDaysWeatherBox) {
  return multipleDaysWeatherBox.query().build();
}
 
Example #21
Source File: DbUtil.java    From weather with Apache License 2.0 2 votes vote down vote up
/**
 * Get query of itemHourlyDBBox according to fiveDayWeatherId value
 *
 * @param itemHourlyDBBox  instance of {@link Box<ItemHourlyDB>}
 * @param fiveDayWeatherId int key of five day weather id
 * @return instance of {@link Query<ItemHourlyDB>}
 */
public static Query<ItemHourlyDB> getItemHourlyDBQuery(Box<ItemHourlyDB> itemHourlyDBBox, long fiveDayWeatherId) {
  return itemHourlyDBBox.query()
      .equal(ItemHourlyDB_.fiveDayWeatherId, fiveDayWeatherId)
      .build();
}
 
Example #22
Source File: DbUtil.java    From weather with Apache License 2.0 2 votes vote down vote up
/**
 * Get query of fiveDayWeatherBox
 *
 * @param fiveDayWeatherBox instance of {@link Box<FiveDayWeather>}
 * @return instance of {@link Query<FiveDayWeather>}
 */
public static Query<FiveDayWeather> getFiveDayWeatherQuery(Box<FiveDayWeather> fiveDayWeatherBox) {
  return fiveDayWeatherBox.query().build();
}
 
Example #23
Source File: DbUtil.java    From weather with Apache License 2.0 2 votes vote down vote up
/**
 * Get query of currentWeatherBox
 *
 * @param currentWeatherBox instance of {@link Box<CurrentWeather>}
 * @return instance of {@link Query<CurrentWeather>}
 */
public static Query<CurrentWeather> getCurrentWeatherQuery(Box<CurrentWeather> currentWeatherBox) {
  return currentWeatherBox.query().build();
}