继承HibernateDaoSupport有三种方式:
1.
- @Component("logDAO")
- public class LogDAOImpl extends HibernateDaoSupport implements LogDAO {
- public void save(Log log) {
- this.getHibernateTemplate().save(log);
- }
- }
xml中注入:
- <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
- <property name="sessionFactory" ref="sessionFactory"></property>
- </bean>
- <bean id="logDao" class="com.zchen.spring.LogDaoImpl">
- <property name="hibernateTemplate" ref="hibernateTemplate"></property>
- </bean>
也可以直接注入SessionFactory
- <bean id="logDao" class="com.zchen.spring.LogDaoImpl">
- <property name="sessionFactory" ref="sessionFactory"></property>
- </bean>
这样一来每个daoImpl都要在bean.xml中注入所以第二种方式就是:
2.
- import javax.annotation.Resource;
- import org.springframework.orm.hibernate3.HibernateTemplate;
- import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
- import org.springframework.stereotype.Component;
- @Component
- public class SuperDAO {
- private HibernateTemplate hibernateTemplate;
- public HibernateTemplate getHibernateTemplate() {
- return hibernateTemplate;
- }
- @Resource
- public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
- this.hibernateTemplate = hibernateTemplate;
- }
- }
所有的daoImpl都继承自SuperDao
- package com.zchen.dao.impl;
- import javax.annotation.Resource;
- import org.hibernate.Session;
- import org.springframework.orm.hibernate3.HibernateTemplate;
- import org.springframework.stereotype.Component;
- import com.zchen.dao.UserDAO;
- import com.zchen.model.User;
- @Component("urseDao") public class UserDAOImpl extends SuperDAO implements UserDAO {
- public void save(User user) {
- this.getHibernateTemplate().save(user);
- }
- }
- <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
- <property name="sessionFactory" ref="sessionFactory"></property>
- </bean>
3继承sessionFactory
- import javax.annotation.Resource;
- import org.hibernate.SessionFactory;
- import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
- import org.springframework.stereotype.Component;
- @Component
- public class SuperDAO extends HibernateDaoSupport {
- @Resource(name="sessionFactory")
- public void setSuperSessionFactory(SessionFactory sessionFactory) {
- super.setSessionFactory(sessionFactory);
- }
- }
继承hibernateTemplate也是一样的
- @Component
- public class SuperDAO extends HibernateDaoSupport {
- @Resource(name="hibernateTemplate")
- public void setSuperHibernateTemplate(HibernateTemplate hibernateTemplate) {
- super.setHibernateTemplate(hibernateTemplate);
- }
- }
- @Component("u")
- public class UserDAOImpl extends SuperDAO implements UserDAO {
- public void save(User user) {
- this.getHibernateTemplate().save(user);
- }
- }
如果继承hibernateTemplate要配置bean
<bean id="userDao" class="com.zchen.spring.UserDaoImpl">
<property name="hibernateTemplate" ref="hibernateTemplate"></property>
</bean>