日期:2014-05-20 浏览次数:20783 次
public interface GenericDao<T> { public void save(T entity); public void remove(T entity); public void modify(T entity); }
public class GenericDaoImpl<T> implements GenericDao<T> { private Class<T> type; private HibernateTemplate hibernateTemplate; public GenericDaoImpl(Class<T> type) { this.type = type; } public GenericDaoImpl(){} public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } public HibernateTemplate getHibernateTemplate() { return hibernateTemplate; } public void modify(T entity) { hibernateTemplate.update(entity); } public void remove(T entity) { hibernateTemplate.delete(entity); } public void save(T entity) { hibernateTemplate.save(entity); } }
public interface GenericService<T> { public void save(T entity); public void remove(T entity); public void modify(T entity); }
public class GenericServiceImpl<T> implements GenericService<T> { private GenericDao<T> genericDao; public void modify(T entity) { genericDao.modify(entity); } public void remove(T entity) { genericDao.remove(entity); } public void save(T entity) { genericDao.save(entity); } public void setGenericDao(GenericDao<T> genericDao) { this.genericDao = genericDao; } }
public interface UserDao extends GenericDao<User>{ public User findByNameExact(String uname); }
public class UserDaoImpl extends GenericDaoImpl<User> implements UserDao { public UserDaoImpl(){ super(User.class); } public User findByNameExact(String uname) {System.out.println("aa"); List<User> list = (List<User>) this.getHibernateTemplate().find( "from User where userName = '"+uname+"'"); return (!list.isEmpty() && list.size() == 1) ? list.get(0) : null; } }
public interface UserService extends GenericService<User>{ public User exist(String userName); }
public class UserServiceImpl extends GenericServiceImpl<User> implements UserService{ private UserDao userDao; public UserDao getUserDao() { return userDao; } public void setUserDao(UserDao userDao) { this.userDao = userDao; } public User exist(String userName) { // TODO Auto-generated method stub return userDao.findByNameExact(userName); } }
<beans> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <bean id="genericDao" abstract="true"> <property name="hibernateTemplate" ref="hibernateTemplate" /> </bean> <bean id="userDao" class="com.yourpackage.UserDaoImpl" parent="genericDao"> </bean> </beans>