ORMLite Data Access Object(DAO)
Previous time, I wrote about ORMLite to create Table without schema. Next is DAO.
DAO is Data Access Object to manage(CRUD, create read, update, delete).
Before starting, Entity is changed a bit.
Entitiy
Added getter and setter to access
@DatabaseTable(tableName = "setting" ) public class Setting { @DatabaseField(generatedId=true) // For Autoincrement private Integer id; @DatabaseField private String key; @DatabaseField private Integer value; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public Integer getValue() { return value; } public void setValue(Integer value) { this.value = value; } }
DAO
Data Access Object(Example)
public class SettingDAO { public void createSetting( ConnectionSource cs, String key, Integer value ) throws SQLException { Dao<Setting,Integer> dao = DaoManager.createDao(cs, Setting.class); Setting setting = new Setting(); setting.setKey(key); setting.setValue(value); dao.create(setting); } public Setting findById( ConnectionSource cs, Integer id ) throws SQLException { Dao<Setting,Integer> dao = DaoManager.createDao(cs, Setting.class); return dao.queryForId(id); } public Setting findByKey( ConnectionSource cs, String key ) throws SQLException { Setting ret_val = null; Dao<Setting,Integer> dao = DaoManager.createDao(cs, Setting.class); for ( Setting tmp : dao.queryForEq("key", key) ) { ret_val = tmp; } return ret_val; } public List<Setting> getAll ( ConnectionSource cs ) throws SQLException { Dao<Setting,Integer> dao = DaoManager.createDao(cs, Setting.class); return dao.queryForAll(); } public void update ( ConnectionSource cs, Integer id, Integer value ) throws SQLException { Setting setting = findById(cs, id); if ( setting != null ) { Dao<Setting,Integer> dao = DaoManager.createDao(cs, Setting.class); setting.setValue(value); dao.update(setting); } } }
All operations are required to use
Dao<Setting,Integer> dao = DaoManager.createDao(cs, Setting.class);
There are implementation of creating, updating, finding.
Frame
Called from Activity class.
ORMDatabaseHelper dbhelper = new ORMDatabaseHelper(this); ConnectionSource connectionSource = new AndroidConnectionSource(dbhelper); try { // Operation using DAO } finally { if ( connectionSource != null ) { try { connectionSource.close(); } catch ( SQLException oops ) { oops.printStackTrace(); } } }
Create helper and do operations. After getting connection source, you can call DAO.
If you don’t need operations, connection source should be closed. That’s all.