BaseDao

  1. /**
  2. * 所有dao的通用操作,希望所有的dao都继承此类
  3. * @author Jie.Yuan
  4. *
  5. * @param <T>
  6. */
  7. public class BaseDao<T> implements IBaseDao<T> {
  8. // 当前操作的实际的bean类型
  9. private Class<T> clazz;
  10. // 获取类名称
  11. private String className;
  12. // 反射泛型
  13. public BaseDao(){
  14. Type type = this.getClass().getGenericSuperclass();
  15. // 转换为参数化类型
  16. ParameterizedType pt = (ParameterizedType) type; // BaseDao<Employee>
  17. // 得到实际类型
  18. Type types[] = pt.getActualTypeArguments();
  19. // 获取实际类型
  20. clazz = (Class<T>) types[0];
  21. className = clazz.getSimpleName();//例如:Employee
  22. }
  23. // 容器注入
  24. private SessionFactory sessionFactory;
  25. public void setSessionFactory(SessionFactory sessionFactory) {
  26. this.sessionFactory = sessionFactory;
  27. }
  28. public SessionFactory getSessionFactory() {
  29. return sessionFactory;
  30. }
  31. public void delete(int id) {
  32. sessionFactory
  33. .getCurrentSession()
  34. .createQuery("delete from " + className + " where id=?")
  35. .setParameter(0, id).executeUpdate();
  36. }
  37. @SuppressWarnings("unchecked")
  38. public T findById(int id) {
  39. return (T) sessionFactory.getCurrentSession().get(clazz, id);
  40. }
  41. @SuppressWarnings("unchecked")
  42. public List<T> getAll() {
  43. return sessionFactory.getCurrentSession().createQuery("from " + className).list();
  44. }
  45. public void save(T t) {
  46. sessionFactory.getCurrentSession().save(t);
  47. }
  48. public void update(T t) {
  49. sessionFactory.getCurrentSession().update(t);
  50. }
  51. }





posted @ 2016-09-21 16:06  无丑不成戏如人生  阅读(803)  评论(0编辑  收藏  举报