在开发采用Struts2+Spring+hibernate这三大框架的项目时,我们需要一个抽取一个BaseDao。这个Dao里面CRUD都给封装好,后续的其他Dao直接用它的功能就可以。Spring里面有个HibernateDaoSupport的类,这个类需要给他一个SessionFactory。有了SessionFactory后,他就可以做各种操作;最强大的功能是它可以getHibernateTemplate来获取一个HibernateTemplate。有了HibernateTemplate,就有了各种CRUD方法。废话不多说,下面直接看代码

一、BaseDao接口及实现的代码

    (1)BaseDao接口的代码
package com.tax.core.dao;
import java.io.Serializable;
import java.util.List; /**
* BaseDao
* @author ZENG.XIAO.YAN
* @date 2017年6月29日 上午10:36:57
* @version v1.0
*/
public interface BaseDao<T> { /**
* 新增
* @param entity
*/
public void save(T entity); /**
* 更新
* @param entity
*/
public void update(T entity); /**
* 根据id删除
* @param id
*/
public void deleteById(Serializable id); /**
* 通过id查找
* @param id
* @return 实体
*/
public T findById(Serializable id); /**
* 查找所有
* @return List集合
*/
public List<T> findAll();
}
45
 
1
package com.tax.core.dao;
2
import java.io.Serializable; 
3
import java.util.List;
4

5
/**
6
 * BaseDao
7
 * @author ZENG.XIAO.YAN
8
 * @date 2017年6月29日 上午10:36:57
9
 * @version v1.0
10
 */
11
public interface BaseDao<T> {
12

13
    /**
14
     * 新增
15
     * @param entity
16
     */
17
    public void save(T entity);
18

19
    /**
20
     * 更新
21
     * @param entity
22
     */
23
    public void update(T entity);
24

25
    /**
26
     * 根据id删除
27
     * @param id
28
     */
29
    public void deleteById(Serializable id);
30

31
    
32
    /**
33
     * 通过id查找
34
     * @param id
35
     * @return 实体
36
     */
37
    public T findById(Serializable id);
38

39
    
40
    /**
41
     * 查找所有
42
     * @return List集合
43
     */
44
    public List<T> findAll();
45
}
    
    (2)BaseDaoImpl的代码

package com.tax.core.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport; import com.tax.core.dao.BaseDao; /**
* BaseDaoImpl
* @author ZENG.XIAO.YAN
* @date 2017年6月29日 下午12:23:16
* @version v1.0
*/
public abstract class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T> { private Class<T> clazz; // 按照类型自动注入SessionFactory; 在实例化的时候,Spring按照形参的类型自动注入
@Autowired
public void setMySessionFactory(SessionFactory sessionFactory){
setSessionFactory(sessionFactory);
} public BaseDaoImpl() {
//this表示当前被实例化的对象;如UserDaoImpl
ParameterizedType pt = (ParameterizedType)this.getClass().getGenericSuperclass();//BaseDaoImpl<User>
clazz = (Class<T>)pt.getActualTypeArguments()[0];
} /**
* 获取session
* @return session
*/
public Session getCurrentSession(){
Session session = null;
try {
session = getSessionFactory().getCurrentSession();
} catch (HibernateException e) {
throw new RuntimeException("getCurrentSession error", e);
//session = getSessionFactory().openSession();
}
return session;
} @Override
public void save(T entity) {
getHibernateTemplate().save(entity);
} @Override
public void update(T entity) {
getHibernateTemplate().update(entity);
} @Override
public void deleteById(Serializable id) {
getHibernateTemplate().delete(findById(id));
} @Override
public T findById(Serializable id) {
return getHibernateTemplate().get(clazz, id);
}
@Override
public List<T> findAll() {
Session session = getCurrentSession();
Query query = session.createQuery("FROM "+ clazz.getSimpleName());
return query.list();
} }
x
 
1
package com.tax.core.dao.impl;
2

3
import java.io.Serializable;
4
import java.lang.reflect.ParameterizedType;
5
import java.util.List;
6
import org.hibernate.HibernateException;
7
import org.hibernate.Query;
8
import org.hibernate.Session;
9
import org.hibernate.SessionFactory;
10
import org.springframework.beans.factory.annotation.Autowired;
11
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
12

13
import com.tax.core.dao.BaseDao;
14

15
/**
16
 * BaseDaoImpl
17
 * @author   ZENG.XIAO.YAN
18
 * @date     2017年6月29日 下午12:23:16
19
 * @version  v1.0
20
 */
21
public abstract class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T> {
22
    
23
    private Class<T> clazz;
24
    
25
    // 按照类型自动注入SessionFactory; 在实例化的时候,Spring按照形参的类型自动注入
26
    @Autowired
27
    public void setMySessionFactory(SessionFactory sessionFactory){
28
        setSessionFactory(sessionFactory);
29
    }
30
    
31
    
32
    public BaseDaoImpl() {
33
        //this表示当前被实例化的对象;如UserDaoImpl
34
        ParameterizedType pt = (ParameterizedType)this.getClass().getGenericSuperclass();//BaseDaoImpl<User> 
35
        clazz = (Class<T>)pt.getActualTypeArguments()[0];
36
    }
37
    
38
    /**
39
     * 获取session
40
     * @return session
41
     */
42
    public Session getCurrentSession(){
43
        Session session = null;
44
        try {
45
            session = getSessionFactory().getCurrentSession();
46
        } catch (HibernateException e) {
47
            throw new RuntimeException("getCurrentSession error", e);
48
            //session = getSessionFactory().openSession();
49
        }
50
        return session;
51
    }
52
    
53
    @Override
54
    public void save(T entity) {
55
        getHibernateTemplate().save(entity);
56
    }
57
    
58
    @Override
59
    public void update(T entity) {
60
        getHibernateTemplate().update(entity);
61
    }
62
    
63
    @Override
64
    public void deleteById(Serializable id) {
65
        getHibernateTemplate().delete(findById(id));
66
    }
67
    
68
    @Override
69
    public T findById(Serializable id) {
70
        return getHibernateTemplate().get(clazz, id);
71
    }
72
    @Override
73
    public List<T> findAll() {
74
        Session session = getCurrentSession();
75
        Query query = session.createQuery("FROM "+ clazz.getSimpleName());
76
        return query.list();
77
    }
78

79
}

    (3)对BaseDaoImpl的说明
            使用HibernateDaoSupport需要注入SessionFactorytory,这个注入的动作其实可以交给BaseDaoImpl的子类去完成的。
            如:StudentImpl继承了BaseDaoImpl。那么在Spring的xml文件按照下面配置即可
                    
            但是:我觉得这样很麻烦,而且我Dao层我想直接用注解。我不想在每个Dao里都去写这个注入的动作。
            所以就准备在BaseDaoImpl里面去完成这个注入动作。
            下面开始了我的探索之路:
             方案一: 在BaseDaoImpl里面定义SessionFactory的属性,然后属性用注解把它注入。
                            最后在构造器里把这个SessionFactory通过set给HibernateDaoSupport。
                            具体的如下图:
                            
                            结果:虽然想法没问题,但是后面发现在实例化的时候,这个sessionFactory还没注进来。
                                       在项目启动的是时候就报错了,因为我给别人的SessionFactory个设置为null了;所以失败了。
                            后面通过百度发现,原来Spring容器管理的类中,这个@Autowired注入是在对象实例化完成之后。
                            所以对Spring容器对bean的实例化过程的还是需要掌握的,笔者在这块掌握得不好。
                            参考链接:http://blog.csdn.net/xia744510124/article/details/51273576

            方案二: 在BaseDaoImpl中定义一个方法,在方法上加个注解。然后方法中把注解注入的形参(sessionFactory)
                           通过set给HibernateDaoSupport。
                           具体如下图:
                           
                            结果: 注入成功,这个注解是根据形参的类型自动注入的。sessionFactory会在Spring实例化这Dao后注入。
                           参考链接:http://blog.csdn.net/tsingheng/article/details/8847047

            通过这个探索,发现了自己对Spring的知识掌握得不够,不知道用注解来注入是在对象实例化之后。
                    

二、使用写好的BaseDao和BaseImpl

        (1)Dao接口直接继承BaseDao即可,下面以StudentDao接口为例
                 
       (2)Dao的实现类,需要继承BaseDaoImpl,下面以StudentDaoImpl为例
                 

三、结束语

        通过抽取这个BaseDao,后续的CRUD就很方便了。
 

 

                           
 


    

最新文章

  1. Apache error: 403 Forbidden You don&#39;t have permission to access
  2. 引用POPUI来实现弹窗效果,且弹窗中的内容可以点击事件
  3. js高程笔记1-3章
  4. launch failed.Binary not found in Linux/Ubuntu解决方案
  5. 制作第一个UI字体
  6. hdu EXCEL排序
  7. php学习之string
  8. 201521123079《java程序设计》第11周学习总结
  9. CPP--关于long的争议和思考
  10. 使用mybatis插入自增主键ID的数据后返回自增的ID
  11. 【翻译】如何创建Ext JS暗黑主题之二
  12. Hadoop3.2.0使用详解
  13. python中重要的模块--asyncio 转载
  14. React-router4 第八篇 ReactCSSTransitionGroup 动画转换
  15. (zhuan) Attention in Long Short-Term Memory Recurrent Neural Networks
  16. 解决org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource
  17. Android之录音工具类
  18. selenium常用的断言
  19. 使用github搭建个人html网站
  20. C# 源码计数器

热门文章

  1. mvp在flutter中的应用
  2. Fit项目分页组件的编写
  3. 如何在单元测试时隔离ORM
  4. Laravel安装教程
  5. search文件中的config
  6. 推荐linux下的数据库开发工具DBeaver 开源免费
  7. pip 设置国内源
  8. python下wxpython程序国际化的实践(中文英文切换)
  9. pt-heartbeat工具监控MySQL复制延迟
  10. PyQt5--Signal&amp;Slot