使用模板方法模式+私有内部类+匿名类解决各个方法间代码结构类似的问题。
package org.hibernate.dao; import org.hibernate.*; import org.hibernate.entity.*; //使用模板方法模式+私有内部类+匿名类解决各个方法间代码结构类似的问题。 public class UserDAOImpl implements UserDAO { private abstract class UserDAOTemplate{ abstract protected Object operateSession(Session session,Object arg); final public Object operateSessionInTransaction(Object arg){ Object result=null; Session session= HibernateUtil.getSession(); Transaction tx = session.beginTransaction(); try{ result=operateSession(session,arg); tx.commit(); } catch(Exception e){ e.printStackTrace(); tx.rollback(); result=null; }finally{ HibernateUtil. closeSession(); } return result; } } public void save(User user){ new UserDAOTemplate(){ protected Object operateSession(Session session,Object arg){ session.save(arg); return null; } }.operateSessionInTransaction(user); } public User findById(int id){ User user=null; user=(User)new UserDAOTemplate(){ protected Object operateSession(Session session,Object arg){ return session.get(User.class,(Serializable)arg); } }.operateSessionInTransaction(id); return user; } public void delete(User user){ new UserDAOTemplate(){ protected Object operateSession(Session session,Object arg){ session.delete(arg); return null; } }.operateSessionInTransaction(user); } //对比参考用 public void update(User user){ Session session= HibernateUtil.getSession(); Transaction tx = session.beginTransaction(); try{ session.update(user); tx.commit(); } catch(Exception e){ e.printStackTrace(); tx.rollback(); }finally{ HibernateUtil. closeSession(); } } }