Android

ormlite

aucd29 2017. 10. 26. 14:44
realm 을 접한 뒤 sqlite 도 ORM 으로 쓸수 있는게 없을까 하고 찾아봤다.
이와 관련된 몇 가지 lib 이 있기는 하지만 일단 ormlite 로 채택했고 테스트 결과 코틀린에서 약간 문제가 있긴 했지만 아직은 java 코드가 더 많다 보니 큰 문제는 없어 보인다.

java base 에 기존 project 들을 ormlite 로 적용하였고 큰 문제 없이 동작 중이다.
gradle 주소와 sample code 를 남긴다. 자세한 내용은 http://ormlite.com/sqlite_java_android_orm.shtml 를 참고 한다.

gradle
compile 'com.j256.ormlite:ormlite-android:4.48'

base class
public abstract class DbHelperBase<T> extends OrmLiteSqliteOpenHelper {
    private static final Logger mLog = LoggerFactory.getLogger(DbHelperBase.class);

    @SuppressWarnings("WeakerAccess")
    private final Class<T> mType;
    private Dao<T, Integer> mDao = null;

    @SuppressWarnings({"unchecked", "SameParameterValue"})
    protected DbHelperBase(Context context, String databaseName, SQLiteDatabase.CursorFactory factory, int databaseVersion) {
        super(context, databaseName, factory, databaseVersion);

        mType = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    public Dao<T, Integer> dao() {
        try {
            if (mDao == null) {
                mDao = getDao(mType);
            }
        } catch (Exception e) {
            mLog.error("ERROR: " + e.getMessage());
        }

        return mDao;
    }

    @Override
    public void close() {
        mDao = null;

        if (mLog.isDebugEnabled()) {
            mLog.debug("== DB CLOSE ==");
        }

        super.close();
    }

    @Override
    public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
        try {
            TableUtils.createTable(connectionSource, mType);
        } catch (Exception e) {
            e.printStackTrace();
            mLog.error("ERROR: " + e.getMessage());
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
        try {
            TableUtils.dropTable(connectionSource, mType, true);
            onCreate(database, connectionSource);
        } catch (Exception e) {
            e.printStackTrace();
            mLog.error("ERROR: " + e.getMessage());
        }
    }
}

child class
public class DbHelper extends DbHelperBase<Test> {
    private static final Logger mLog = LoggerFactory.getLogger(DbHelper.class);

    private static final String DATABASE_NAME    = "test.db";
    private static final int    DATABASE_VERSION = 1;

    private static DbHelper mInst;

    public static DbHelper get() {
        if (mInst == null) {
            mInst = new DbHelper(BkApp.get().context());

            if (mLog.isDebugEnabled()) {
                mLog.debug("== INIT DB ==");
            }
        }

        return mInst;
    }

    private DbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void close() {
        super.close();

        mInst = null;
    }
}

table class

@DatabaseTable(tableName = "test")
public class Test {
    @DatabaseField
    public String key;

    @DatabaseField
    public String value;
}