public class BaseHibernateDAO { private Session session = null ; private Object get(Class clz , Serializable id){ Object ret = null ; Session session = HibernateSessionFactory.getSession(); try { ret = session.get(clz, id); } catch (HibernateException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ this.closeSession(); } return ret ; } protected void add(Object item){ Transaction tx = null ; Session session = HibernateSessionFactory.getSession(); try { tx = session.beginTransaction(); session.save(item); tx.commit(); } catch (HibernateException e) { // TODO Auto-generated catch block if(tx != null){ tx.rollback(); } e.printStackTrace(); }finally{ closeSession(); } } public void delete(Class clz , Serializable id){ Transaction tx = null ; Session session = HibernateSessionFactory.getSession(); try { tx = session.beginTransaction(); session.delete(this.get(clz, id)); tx.commit(); } catch (HibernateException e) { // TODO Auto-generated catch block if(tx != null){ tx.rollback(); } e.printStackTrace(); }finally{ closeSession(); } } public void update(Object item){ Transaction tx = null ; Session session = HibernateSessionFactory.getSession(); try { tx = session.beginTransaction(); session.update(item); tx.commit(); } catch (HibernateException e) { // TODO Auto-generated catch block if(tx != null){ tx.rollback(); } e.printStackTrace(); }finally{ closeSession(); } } public List search(Class clazz , Object condition){ List results = null ; try { Session session = HibernateSessionFactory.getSession(); results = session.createCriteria(clazz).add(Example.create(condition)).list(); } catch (HibernateException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ closeSession(); } return results; } protected void closeSession(){ this.session = null ; HibernateSessionFactory.closeSession(); } }
按照书上的代码照例打了一份, 说实话 , 很晕, 就先拿 第一个 获取某一个对象的方法来说
private Object get(Class clz , Serializable id){ }
接受的参数居然Class 类型的, 我还是第一次见到 , 而且这个Class ,在实际的DAOImpl 方法中使用的时候
还需要使用 TblUser .class , 不这样用的话 , 即使我已经导入了这个实体类所在的包, 他仍然报错,
"TblUser cannou be resolved" 加了.class 才OK, 回来待弄明白这个事情.
还有这个Serializable , 我以前使用他都是在创建一个实体类的时候 来 implements 的
是由一个类来实现这个接口的, 这里居然是由它声明一个 int 类型的变量, 使之也能够被序列化 .