Skip to content

Instantly share code, notes, and snippets.

@radiocat
Created December 14, 2013 17:54
Show Gist options
  • Save radiocat/7962472 to your computer and use it in GitHub Desktop.
Save radiocat/7962472 to your computer and use it in GitHub Desktop.
AndroidでORマッピングできるOrmLiteの使い方 ref: http://qiita.com/radiocatz/items/5f1dce3f8c5faa55e6f6
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static final String DATABASE_NAME = "ormExample.db";
private static final int DATABASE_VERSION = 1;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
try {
// エンティティを指定してcreate tableします
TableUtils.createTable(connectionSource, Word.class);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "データベースを作成できませんでした", e);
}
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i2) {
// DBのアップグレード処理(今回は割愛)
}
}
@DatabaseTable(tableName = "word")
public class Word {
@DatabaseField(generatedId = true)
private Integer id;
@DatabaseField
private String value;
public Word() {
}
public Word(String value) {
this.value = value;
}
public Integer getId() {
return this.id;
}
public String getValue() {
return this.value;
}
public void setValue(String value) {
this.value = value;
}
}
public void save(Word word) {
DatabaseHelper helper = new DatabaseHelper(context);
try {
Dao<Word, Integer> dao = helper.getDao(Word.class);
dao.createOrUpdate(word);
} catch (Exception e) {
Log.e(TAG, "例外が発生しました", e);
} finally {
helper.close();
}
}
public List<Word> findAll() {
DatabaseHelper helper = new DatabaseHelper(context);
try {
Dao<Word, Integer> dao = helper.getDao(Word.class);
return dao.queryForAll();
} catch (Exception e) {
Log.e(TAG, "例外が発生しました", e);
return null;
} finally {
helper.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment