문서의 선택한 두 판 사이의 차이를 보여줍니다.
— |
java:hibernate:genericdao [2013/08/28 15:30] (현재) kwon37xi 새로 만듦 |
||
---|---|---|---|
줄 1: | 줄 1: | ||
+ | ====== Hibernate Generic Dao ====== | ||
+ | * https:// | ||
+ | |||
+ | ===== Generic Dao Interface ===== | ||
+ | <code java> | ||
+ | public interface GenericDAO< | ||
+ | | ||
+ | T findById(ID id, boolean lock); | ||
+ | | ||
+ | List< | ||
+ | | ||
+ | List< | ||
+ | | ||
+ | T makePersistent(T entity); | ||
+ | | ||
+ | void makeTransient(T entity); | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | ===== Generic Dao class ===== | ||
+ | <code java> | ||
+ | public abstract class GenericHibernateDAO< | ||
+ | implements GenericDAO< | ||
+ | | ||
+ | private Class< | ||
+ | private Session session; | ||
+ | | ||
+ | public GenericHibernateDAO() { | ||
+ | this.persistentClass = (Class< | ||
+ | .getGenericSuperclass()).getActualTypeArguments()[0]; | ||
+ | | ||
+ | | ||
+ | @SuppressWarnings(" | ||
+ | public void setSession(Session s) { | ||
+ | this.session = s; | ||
+ | } | ||
+ | | ||
+ | protected Session getSession() { | ||
+ | if (session == null) | ||
+ | throw new IllegalStateException(" | ||
+ | return session; | ||
+ | } | ||
+ | | ||
+ | public Class< | ||
+ | return persistentClass; | ||
+ | } | ||
+ | | ||
+ | @SuppressWarnings(" | ||
+ | public T findById(ID id, boolean lock) { | ||
+ | T entity; | ||
+ | if (lock) | ||
+ | entity = (T) getSession().load(getPersistentClass(), | ||
+ | else | ||
+ | entity = (T) getSession().load(getPersistentClass(), | ||
+ | | ||
+ | return entity; | ||
+ | } | ||
+ | | ||
+ | @SuppressWarnings(" | ||
+ | public List< | ||
+ | return findByCriteria(); | ||
+ | } | ||
+ | | ||
+ | @SuppressWarnings(" | ||
+ | public List< | ||
+ | Criteria crit = getSession().createCriteria(getPersistentClass()); | ||
+ | Example example = Example.create(exampleInstance); | ||
+ | for (String exclude : excludeProperty) { | ||
+ | example.excludeProperty(exclude); | ||
+ | } | ||
+ | crit.add(example); | ||
+ | return crit.list(); | ||
+ | } | ||
+ | | ||
+ | @SuppressWarnings(" | ||
+ | public T makePersistent(T entity) { | ||
+ | getSession().saveOrUpdate(entity); | ||
+ | return entity; | ||
+ | } | ||
+ | | ||
+ | public void makeTransient(T entity) { | ||
+ | getSession().delete(entity); | ||
+ | } | ||
+ | | ||
+ | public void flush() { | ||
+ | getSession().flush(); | ||
+ | } | ||
+ | | ||
+ | public void clear() { | ||
+ | getSession().clear(); | ||
+ | } | ||
+ | | ||
+ | /** | ||
+ | * Use this inside subclasses as a convenience method. | ||
+ | | ||
+ | @SuppressWarnings(" | ||
+ | protected List< | ||
+ | Criteria crit = getSession().createCriteria(getPersistentClass()); | ||
+ | for (Criterion c : criterion) { | ||
+ | crit.add(c); | ||
+ | } | ||
+ | return crit.list(); | ||
+ | | ||
+ | | ||
+ | } | ||
+ | </ | ||