Skip to content

Instantly share code, notes, and snippets.

@adilold
Created November 14, 2012 21:56
Show Gist options
  • Save adilold/4075110 to your computer and use it in GitHub Desktop.
Save adilold/4075110 to your computer and use it in GitHub Desktop.
Generic DAO using Java generics! :D
/**
* Establishes the DAO pattern for use with other classes.
* @author Adil
*
*/
public class GenericDao<T> {
@SuppressWarnings("unchecked")
/**
* Load an item by its ID (primary key).
* @param item Type of item
* @param id The id of the item
* @return The item
*/
public T loadById(T item, Integer id) {
// typecheck
if(item instanceof Class<?>) {
return (T)Shark.getDataStore().openSession().load(getType(item),id);
}
return null;
}
public void saveOrUpdate(T item) {
Shark.getDataStore().openSession().saveOrUpdate(item);
}
public void delete(T item) {
Shark.getDataStore().openSession().delete(item);
}
public Class<? extends Object> getType(T item) {
return item.getClass();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment