Skip to content

Instantly share code, notes, and snippets.

@Jinz0
Forked from adilold/GenericDao.java
Created November 14, 2012 22:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jinz0/4075390 to your computer and use it in GitHub Desktop.
Save Jinz0/4075390 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 <adil.h@me.com>
*
*/
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