OR Mapper ORMLiteを使ってみる - Daoの使用例-

※このページは追記予定です。

queryForAll 全件取得

Dao<Account, Integer> dao = getHelper().getDao(Account.class);
dao.querForAll();

queryForFirst 最初に一致したEntityの取得

displayOrderが最小のAccountを取得
// daoの取得はquerForAllを参照
Account account = dao.queryForFirst(dao.queryBuilder().orderBy("displayOrder", true).prepare());
displayOrderが最大のAccountを取得
// daoの取得はquerForAllを参照
Account account = dao.queryForFirst(dao.queryBuilder().orderBy("displayOrder", false).prepare());

createIfNotExists 無ければつくり、あればもってくる(更新ではない!)

既に同じIDのentityがDBに存在する場合
Account ac1 = new Account("account1", "pass1", 1);
dao.create(ac1);

// ac1と同じIDのAccount
Account ac2 = new Account(ac1.name, "pass2", 2);
ac2 = dao.createIfNotExists(ac2);
Log.i("Account", ac2.toString());

実行結果
name[account1] password [pass1]
updateされるのではなく、事前にcreateしたac1になる。
ac2の値でDBを上書きしたい場合はcreateOrUpdate()を使う。

同じIDのentityがDBに存在しない場合

通常のcreateと同じ動作なので省略。

サンプルで使っているEntity

@DatabaseTable
public class Account {
	
    @DatabaseField(id = true)
    public String name;
    
    @DatabaseField(canBeNull = false)
    public String password;
    
    @DatabaseField(canBeNull = false)
    public int displayOrder;
    
    public Account() {
    }
    
    public Account(String name, String password, int displayOrder) {
        this.name = name;
        this.password = password;
        this.displayOrder = displayOrder;
    }

    public String toString() {
    	return "name[" + name + "] password [" + password + "]";
    }
}