ssh整合之HibernateDaoSupport的使用
阿新 • • 發佈:2019-02-02
繼承HibernateDaoSupport有三種方式:
1.
Java程式碼- @Component("logDAO")
- public class LogDAOImpl extends HibernateDaoSupport implements LogDAO {
- public void save(Log log) {
- this.getHibernateTemplate().save(log);
- }
- }
xml中注入:
Java程式碼-
<bean id="hibernateTemplate"
- <property name="sessionFactory" ref="sessionFactory"></property>
- </bean>
- <bean id="logDao" class="com.zchen.spring.LogDaoImpl">
-
<property name="hibernateTemplate" ref="hibernateTemplate"></property>
- </bean>
也可以直接注入SessionFactory
Java程式碼- <bean id="logDao" class="com.zchen.spring.LogDaoImpl">
- <property name="sessionFactory" ref="sessionFactory"></property>
- </bean>
這樣一來每個daoImpl都要在bean.xml中注入所以第二種方式就是:
2.
Java程式碼-
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
Java程式碼- 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
Java程式碼- 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也是一樣的
Java程式碼- @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>