在开发采用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就很方便了。
 

 

                           
 


    

使用HibernateDaoSupport抽取BaseDao的更多相关文章

  1. 案例50-crm练习dao层的抽取BaseDao

    1 抽取BaseDao 2 BaseDao设计思路 3 BaseDao接口书写 package www.test.dao; import java.io.Serializable; import ja ...

  2. Dao层抽取BaseDao公共方法

    设计IBseDao接口,定义公共的CRUD方法. // IBaseDao 接口,定义公共的CRUD方法 public interface IBaseDao<T> { public void ...

  3. Hibernate抽取BaseDao

    package com.cky.dao; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate. ...

  4. ssm框架整合抽取BaseDao接口

    import java.io.Serializable; import java.util.List; /** * DAO基础操作模板 * * @param <T> 泛型 */ publi ...

  5. JAVAEE——SSH项目实战02:客户列表和BaseDao封装

    作者: kent鹏 转载请注明出处: http://www.cnblogs.com/xieyupeng/p/7129152.html 该项目在SSH三大框架整合基础上进行开发:http://www.c ...

  6. JavaEE笔记——BaseDao的使用

    在Hibernate框架中使用BaseDao主要的作用是减少冗余代码,在对Dao的操作中CRUD可以说是最普通最常见的操作了,基本上面对不同的数据表都会有类似的CRUD操作,BaseDao的思想就是把 ...

  7. (六)编写基类BaseDao

    在action中继承了ActionSupport和其它一些公共属性,如selectedRow等:可能以后还会产生更多公共的内容,所以应该把这些共有的抽取出来,放入到一个基本action中,我们命名为B ...

  8. 公共dao的抽取

    package cn.sxx.dao; import java.util.List; import cn.sxx.model.Dep; import cn.sxx.query.DepQuery; pu ...

  9. 利用泛型抽取Dao层,加事务注解问题(java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType)

    想利用泛型抽取BaseDao层,简化操作时出现故障: @Transactional这个注解是能够继承的.于是就想写在抽取的BaseDao层上,让实现的类能够不用写@Transactional,就可开启 ...

随机推荐

  1. as 打包报错

    错误:Android Error:Execution failed for task ':app:transformClassesAndResourcesWithProguardForRelease' ...

  2. Android--WebView 自适应代码

    //WebView自适应代码 private String getHtmlData(String bodyHTML) { String head = "<head>" ...

  3. 前端开发使用Photoshop切图详细步骤

    切图的主要目的是从设计师提供的psd中获取网页制作所要的资源 一.界面设置 1. 新建文件,调整界面大小,背景设置为透明 2. 自动选择,把组切换为图层 3. 添加窗口内容,一共四项:图层.历史纪录. ...

  4. aix rootvg镜像

    就一般生产系统而已,操作系统层面都要进行备份,而最常见的操作系统备份方式之一就是做镜像(mirror),而实践过程中,往往是把rootvg这个卷组做镜像操作.查看rootvg是否已经进行镜像方法: 1 ...

  5. c#中Indexof()和Split()的用法

    C#中IndexOf的使用 indexOf() 查找字串中指定字符或字串首次出现的位置,返首索引值,如: str1.IndexOf("字"): //查找“字”在str1中的索引值( ...

  6. "System.OutOfMemoryException" exception when you execute a query in SQL Server Management Studio (转自MSDN)

    Symptoms When you use Microsoft SQL Server Management Studio (SSMS) to run an SQL query that returns ...

  7. 总结Linux 下Redis 操作常用命令(转)

    Redis的配置 Linux下安装 ]# wget http://download.redis.io/releases/redis-2.8.17.tar.gz ]# tar xzf redis-2.8 ...

  8. 无法获取链接服务器 "XXX" 的 OLE DB 访问接口 "SQLNCLI10" 的架构行集 "DBSCHEMA_TABLES_INFO"。该访问接口支持该接口,但使用该接口时返回了失败代码。

    1. SQL 2000 下载补丁 SQL2KSP4 ,进行安装 2.找到SQL2KSP4\install\instcat.sql 并在sql2000 中打开查询分析器中执行

  9. 16. 窗口函数 (Window Function) 的使用

    从SQL Server 2005起,SQL Server开始支持窗口函数 (Window Function),以及到SQL Server 2012,窗口函数功能增强,目前为止支持以下几种窗口函数: 1 ...

  10. python基础学习8----文件基本操作

    一.文件的打开,open函数 f = open(file_name,mode)#创建文件对象 打开模式有很多种 1. 'r': 以只读方式打开文件.文件的指针将会放在文件的开头.这是默认模式. 2. ...