AndroidでもORMを使いたいなーと思って探してみたら、ormliteというのがあった!
ということで、AndroidStudioで使うときの備忘録。
build.gradleに追加
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.j256.ormlite:ormlite-core:4.23' compile 'com.j256.ormlite:ormlite-android:4.48' }
Entityクラス
サンプルはこんな感じ。
@DatabaseTable(tableName = BookEntity.TABLE_NAME) public class BookEntity { public static final String TABLE_NAME = "book"; public static final String BOOK_ID = "book_id"; public static final String BOOK_TITLE = "book_title"; public static final String BOOK_AUTHOR = "book_author"; @DatabaseField(generatedId = true, columnName = BOOK_ID) private Long bookId; @DatabaseField(columnName = BOOK_ISBN) private String bookTitle; @DatabaseField(columnName = BOOK_AUTHOR, defaultValue = "") private String bookAuthor; }
DBHelperクラス
public class DBHelper extends OrmLiteSqliteOpenHelper { protected final static Integer DB_VERSION = 2; protected final static String DB_NAME = "mydatabase.db"; public DBHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } public DBHelper(Context context, int dbVersion) { super(context, DB_NAME, null, dbVersion); } @Override public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) { try { TableUtils.createTable(connectionSource, BookEntity.class); } catch (SQLException e) { Log.e(DBHelper.class.getName(), "データベースを作成できませんでした", e); } } @Override public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) { Dao<BookEntity, Integer> dao = null; try { dao = getDao(BookEntity.class); if (oldVersion < 2) { // we added the age column in version 2 dao.executeRaw("ALTER TABLE `" + BookDto.TABLE_NAME + "` ADD COLUMN " + BookDto.BOOK_WATCH + " Integer DEFAULT 0;"); } } catch (SQLException e) { Log.e(DBHelper.class.getName(), "データベースを更新できませんでした", e); } }
Daoクラス
SELECT
// Daoの生成 DBHelper helper = new DBHelper(context); Dao<BookEntity, Integer> dao = helper.getDao(BookEntity.class); //全レコード取得 List<BookEntity> result_list = dao.queryForAll(); //1件取得 BookEntity result = dao.queryBuilder() .where() .eq(BookEntity.BOOK_ID, 1) .queryForFirst(); //複数件取得 List<BookEntity> result_list = dao.queryBuilder() .orderBy(BookEntity.BOOK_AUTHOR, true) .orderBy(BookEntity.BOOK_TITLE, true) .where() .like(BookEntity.BOOK_AUTHOR, "Joe %") .query(); //ページング int PAGING_LIMIT = 20; int page = 1; List<BookEntity> result_list = dao.queryBuilder() .offset((page - 1) * PAGING_LIMIT) .limit(PAGING_LIMIT) .query();
INSERT, UPDATE
DBHelper helper = new DBHelper(context); Dao<BookEntity, Integer> dao = helper.getDao(BookEntity.class); //INSERT BookEntity dto = ...; int return_id = dao.create(dto); //INSERT or UPDATE int num_lines_changed = dao.createOrUpdate(dto).getNumLinesChanged();
DELETE
DBHelper helper = new DBHelper(context); Dao<BookEntity, Integer> dao = helper.getDao(BookEntity.class); DeleteBuilder<BookEntity, Integer> builder = dao.deleteBuilder(); builder.where().eq(BookEntity.BOOK_ID, 1);