Skip to content

Commit

Permalink
Additional check that key can be acquired (issue #5)
Browse files Browse the repository at this point in the history
  • Loading branch information
greenrobot committed Feb 13, 2012
1 parent c94df12 commit 483bc3f
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions DaoCore/src/de/greenrobot/dao/AbstractDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,8 @@ public List<T> loadAll() {
/** Detaches an entity from the identity scope (session). Subsequent query results won't return this object. */
public boolean detach(T entity) {
if (identityScope != null) {
return identityScope.detach(getKey(entity), entity);
K key = getKeyVerified(entity);
return identityScope.detach(key, entity);
} else {
return false;
}
Expand Down Expand Up @@ -379,7 +380,7 @@ public void deleteAll() {
/** Deletes the given entity from the database. Currently, only single value PK entities are supported. */
public void delete(T entity) {
assertSinglePk();
K key = getKey(entity);
K key = getKeyVerified(entity);
deleteByKey(key);
if (identityScope != null) {
identityScope.remove(key);
Expand All @@ -406,7 +407,7 @@ public void deleteByKey(K key) {
/** Resets all locally changed properties of the entity by reloading the values from the database. */
public void refresh(T entity) {
assertSinglePk();
K key = getKey(entity);
K key = getKeyVerified(entity);
String sql = statements.getSelectByKey();
String[] keyArray = new String[] { key.toString() };
Cursor cursor = db.rawQuery(sql, keyArray);
Expand Down Expand Up @@ -521,6 +522,20 @@ public long count() {
return DatabaseUtils.queryNumEntries(db, '\'' + config.tablename + '\'');
}

/** See {@link #getKey(Object)}, but guarantees that the returned key is never null (throws if null). */
protected K getKeyVerified(T entity) {
K key = getKey(entity);
if (key == null) {
if (entity == null) {
throw new NullPointerException("Entity may not be null");
} else {
throw new DaoException("Entity has no key");
}
} else {
return key;
}
}

/** Reads the values from the current position of the given cursor and returns a new entity. */
abstract protected T readEntity(Cursor cursor, int offset);

Expand Down

0 comments on commit 483bc3f

Please sign in to comment.