ObjectBox.java 2.57 KB
package com.polysoft.nafmii.database;

import com.polysoft.nafmii.database.entity.DataEntity;
import com.polysoft.nafmii.database.entity.DataEntity_;
import com.polysoft.nafmii.utils.CtxUtils;

import java.util.Date;
import java.util.List;

import io.objectbox.Box;
import io.objectbox.BoxStore;
import io.objectbox.query.QueryBuilder;

public abstract class ObjectBox<T> {
    private static BoxStore mBoxStore;
    private static Box<DataEntity> mDataBox;

    public static synchronized BoxStore getStore() {
        if (null == mBoxStore) {
            mBoxStore = MyObjectBox.builder()
                    .androidContext(CtxUtils.getApplication())
                    .build();
        }
        return mBoxStore;
    }

    public synchronized static Box<DataEntity> getDataBox() {
        if (null == mDataBox) {
            mDataBox = getStore().boxFor(DataEntity.class);
        }
        return mDataBox;
    }

    public static QueryBuilder<DataEntity> newQuery() {
        return getDataBox().query();
    }

    public static DataEntity findById(long id) {
        return newQuery().equal(DataEntity_.id, id).build().findFirst();
    }

    public synchronized static DataEntity findByName(String name) {
        return newQuery().equal(DataEntity_.name, name).build().findFirst();
    }
    public static List<DataEntity> findByNames(String name) {
        return newQuery().equal(DataEntity_.name, name).build().find();
    }

    public static List<DataEntity> findList(DataEntity ...data) {
        QueryBuilder<DataEntity> query = newQuery();
        for (int i = 0; i < data.length; i++) {
            query.equal(DataEntity_.name, data[i].getName());
            if ((i + 1) < data.length) {
                query.or();
            }
        }
        return query.build().find();
    }

    public static synchronized void put(DataEntity ...data) {
        for (DataEntity item : data) {
            DataEntity entity = findByName(item.getName());
            if (null != entity) {
                entity.setUpdateDate(new Date());
                entity.setValue(item.getValue());
                getDataBox().put(entity);
            } else {
                getDataBox().put(item);
            }
        }
    }

    public static synchronized void delete(long... ids) {
        getDataBox().remove(ids);
    }

    public static synchronized void delete(DataEntity... data) {
        for (DataEntity datum : data) {
            List<DataEntity> byNames = findByNames(datum.getName());
            for (DataEntity byName : byNames) {
                delete(byName.getId());
            }
        }
    }
}