getHibernateTemplate()
NUll,困扰好几天了,网上也找了好些方法一直解决不掉
15

小弟刚刚开始学SSH,是用的Struts2+Hibernate+Spring,运行的时候发现getHibernateTemplate()得到的模板类始终是nUll值,郁闷好几天了,一直在我网上试各种方法,迄今任为解决,恳请各位指教咯!

applicationContext.xml:事务处理这儿没贴出来)

Java代码  

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xmlns:tx="http://www.springframework.org/schema/tx"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
  8. http://www.springframework.org/schema/tx
  9. http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
  10. 10.
             http://www.springframework.org/schema/aop
  11. 11.
             http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
  12. 12.
        <!-- 定义数据源 -->
  13. 13.
        <bean id="dataSource"
  14. 14.
            class="org.apache.commons.dbcp.BasicDataSource">
  15. 15.
            <property name="driverClassName"
  16. 16.
                value="com.mysql.jdbc.Driver">
  17. 17.
            </property>
  18. 18.
            <property name="url" value="jdbc:mysql://localhost:3306/jjufriend"></property>
  19. 19.
            <property name="username" value="root"></property>
  20. 20.
            <property name="password" value="root"></property>
  21. 21.
        </bean>
  22. 22.
  23. 23.
        <!-- 定义Hibernate的sessionFactory -->
  24. 24.
        <bean id="sessionFactory"
  25. 25.
            class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  26. 26.
            <property name="dataSource">
  27. 27.
                <ref bean="dataSource" />
  28. 28.
            </property>
  29. 29.
  30. 30.
            <!-- Hibernate  的sessionFactory的属性 -->
  31. 31.
  32. 32.
            <property name="hibernateProperties">
  33. 33.
                <props>
  34. 34.
                    <!-- 数据库方言 -->
  35. 35.
                    <prop key="hibernate.dialect">
  36. 36.
                        org.hibernate.dialect.SQLServerDialect
  37. 37.
                    </prop>
  38. 38.
                    <!-- 显示Hibernate持久化操作所生成的SQL语句 -->
  39. 39.
                    <prop key="hibernate.show_sql">true</prop>
  40. 40.
                    <!-- 将SQL脚本进行格式化后再输出 -->
  41. 41.
                    <prop key="hibernate.format_sql">true</prop>
  42. 42.
                </props>
  43. 43.
            </property>
  44. 44.
            <!-- 列出全部的映射文件 -->
  45. 45.
            <property name="mappingResources">
  46. 46.
                <list>
  47. 47.
                    <value>com/jjufriend/student/model/Student.hbm.xml</value></list>
  48. 48.
            </property></bean>
  49. 49.
  50. 50.
        <!-- 配置dao组件 -->
  51. 51.
        <bean id="studentDao"
  52. 52.
            class="com.jjufriend.student.dao.impl.StudentDaoHibernate">
  53. 53.
            <!-- 依赖注入DAO组件所必需的SessionFactory引用 -->
  54. 54.
            <property name="sessionFactory" ref="sessionFactory">
  55. 55.
            </property>
  56. 56.
        </bean>
  57. 57.
        <!-- 配置业务逻辑组件 -->
  58. 58.
        <bean id="mgr"
  59. 59.
            class="com.jjufriend.student.service.impl.StudentManagerImpl">
  60. 60.
            <property name="studentDao" ref="studentDao"></property>
  61. 61.
        </bean>
  62. 62.

studentDao.java:

Java代码  

  1. package com.jjufriend.student.dao;
  2. import java.util.List;
  3. import com.jjufriend.student.model.Student;
  4. public interface StudentDao {
  5. Student get(Integer id);
  6. 10.
  7. 11.
        Integer save(Student student);
  8. 12.
  9. 13.
        void update(Student student);
  10. 14.
  11. 15.
        void delete(Student student);
  12. 16.
  13. 17.
        void delete(Integer id);
  14. 18.
  15. 19.
        List<Student> findAll();
  16. 20.
  17. 21.
        Student findStudentByNameAndPass(String username,String password);
  18. 22.
  19. 23.
        Student findByName(String username);
  20. 24.

25.
}

StudentDaoHibernate.java:

Java代码  

  1. package com.jjufriend.student.dao.impl;
  2. import java.io.Serializable;
  3. import java.util.List;
  4. import org.hibernate.SessionFactory;
  5. import org.springframework.orm.hibernate3.HibernateTemplate;
  6. import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

10.
import com.jjufriend.student.dao.StudentDao;

11.
import com.jjufriend.student.model.Student;

  1. 12.

13.
public class StudentDaoHibernate extends HibernateDaoSupport implements

  1. 14.
            StudentDao,Serializable {
  2. 15.
        private SessionFactory sessionFactory;
  3. 16.
        HibernateTemplate ht = this.getHibernateTemplate() ;
  4. 17.
  5. 18.
  6. 19.
  7. 20.
        public void delete(Student student) {
  8. 21.
            // TODO Auto-generated method stub
  9. 22.
            getHibernateTemplate().delete(student);
  10. 23.
  11. 24.
        }
  12. 25.
  13. 26.
        public void delete(Integer id) {
  14. 27.
            // TODO Auto-generated method stub
  15. 28.
            getHibernateTemplate().delete(get(id));
  16. 29.
  17. 30.
        }
  18. 31.
  19. 32.
        public List<Student> findAll() {
  20. 33.
            // TODO Auto-generated method stub
  21. 34.
            return (List<Student>)getHibernateTemplate().find("from Student");
  22. 35.
  23. 36.
        }
  24. 37.
  25. 38.
        public Student findByName(String username) {
  26. 39.
  27. 40.
            List stu =  getHibernateTemplate().find("from Student st where st.username = ?",username);
  28. 41.
  29. 42.
            if(stu != null && stu.size() >= 1){
  30. 43.
                return (Student)stu.get(0);
  31. 44.
            }
  32. 45.
  33. 46.
            return null;
  34. 47.
        }
  35. 48.
  36. 49.
        public Student findStudentByNameAndPass(String username, String password) {
  37. 50.
            // TODO Auto-generated method stub
  38. 51.
            List students = null;
  39. 52.
            try{
  40. 53.
  41. 54.
            //  HibernateTemplate temple = this.getHibernateTemplate();

55.
System.out.println("模板类是否为NULL>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+ht);

  1. 56.

57.
//  取出所有        students = temple.find("from student");

  1. 58.
                            students = ht.find("from student st where st.username = " + username + " and st.password = " + password);
  2. 59.
  3. 60.
            }catch(Exception  e){
  4. 61.
                System.out.println("查找过程中出现异常..............");
  5. 62.
                e.printStackTrace();
  6. 63.
            }
  7. 64.
            if(students != null && students.size() >= 1){
  8. 65.
                return (Student)students.get(0);
  9. 66.
                }
  10. 67.
            return null;
  11. 68.
        }
  12. 69.
  13. 70.
        public Student get(Integer id) {
  14. 71.
  15. 72.
            return (Student)getHibernateTemplate().get(Student.class, id);
  16. 73.
  17. 74.
        }
  18. 75.
  19. 76.
        public Integer save(Student student) {
  20. 77.
            return (Integer)getHibernateTemplate().save(student);
  21. 78.
        }
  22. 79.
  23. 80.
        public void update(Student student) {
  24. 81.
            // TODO Auto-generated method stub
  25. 82.
            getHibernateTemplate().update(student);
  26. 83.
  27. 84.
        }
  28. 85.

86.
}

StudentManager.java:

Java代码  

  1. package com.jjufriend.student.service;
  2. import com.jjufriend.student.model.Student;
  3. public interface StudentManager {
  4. int addStudent(Student student) throws Exception;
  5. int loginValid(Student student) throws Exception;
  6. 10.
  7. 11.
        boolean validateName(String username) throws Exception;

12.
}

StudentManagerImpl.java:

Java代码  

  1. package com.jjufriend.student.service.impl;
  2. import com.jjufriend.student.dao.StudentDao;
  3. import com.jjufriend.student.dao.impl.StudentDaoHibernate;
  4. import com.jjufriend.student.model.Student;
  5. import com.jjufriend.student.service.StudentManager;
  6. public class StudentManagerImpl implements StudentManager {
  7. /*2009-11-12 22:44修改 出去new StudentDaoHibernate()    */
  8. 10.
        private StudentDao studentDao = new StudentDaoHibernate() ;
  9. 11.

12.
//  private ApplicationContext cxt =

13.
//          new FileSystemXmlApplicationContext("../webapps/JJUFriend/WEB-INF/applicationContext.xml");

14.
//   studentDao =(StudentDaoHibernate)cxt.getBean("studentDao");

  1. 15.
  2. 16.
        public void setStudentDao(StudentDao studentDao){
  3. 17.
  4. 18.
            this.studentDao = studentDao ;
  5. 19.
        }
  6. 20.
  7. 21.
  8. 22.
        public int addStudent(Student student) throws Exception {
  9. 23.
            // TODO Auto-generated method stub
  10. 24.
            try{
  11. 25.
                studentDao.save(student);
  12. 26.
                return student.getId();
  13. 27.
  14. 28.
            }catch(Exception e){
  15. 29.
                e.printStackTrace();
  16. 30.
                throw new Exception("新增用户时出现异常");
  17. 31.
            }
  18. 32.
  19. 33.
        }
  20. 34.
  21. 35.
        public int loginValid(Student student) throws Exception {
  22. 36.
            try{
  23. 37.

38.
System.out.println(studentDao);

39.
System.out.println("是否取到页面提交的数据:Name="+student.getUsername());

  1. 40.
                Student stu = studentDao.findStudentByNameAndPass(student.getUsername(), student.getPassword());
  2. 41.
                if(stu != null ){
  3. 42.
                    return stu.getId();
  4. 43.
                }
  5. 44.
  6. 45.
            }catch(Exception e){
  7. 46.
                System.out.println("验证用户登录时出现异常");
  8. 47.
                e.printStackTrace();
  9. 48.
            }
  10. 49.
  11. 50.
            // TODO Auto-generated method stub
  12. 51.
            return -1;
  13. 52.
        }
  14. 53.
  15. 54.
        public boolean validateName(String username) throws Exception {
  16. 55.
            // TODO Auto-generated method stub
  17. 56.
            try{
  18. 57.
                if (studentDao.findByName(username) != null){
  19. 58.
                    return true ;
  20. 59.
                }
  21. 60.
  22. 61.
  23. 62.
            }catch(Exception e){
  24. 63.
                System.out.println("验证用户名是否用效时出错");
  25. 64.
                e.printStackTrace();
  26. 65.
  27. 66.
            }
  28. 67.
            return false ;
  29. 68.
  30. 69.
        }
  31. 70.

71.
}

问题的关键是通过方法getHibernateTemplate()不能正确得到HibernateTemplate对象,始终的空值,网上有很多解决的办法,差不多我都试过了,

下面这种方法是说不能直接new StudentDao对象,用下面这种方法取得,可以启动服务器老是不停地跳动,一直不停,直到报错。

Java代码  

  1. //  private ApplicationContext cxt =
  2. //  new FileSystemXmlApplicationContext("../webapps/JJUFriend/WEB-INF/applicationContext.xml");
  3. //  private StudentDao studentDao =(StudentDaoHibernate)cxt.getBean("studentDao");

还有些方法是直接从applicationContext.xml中的bean取得HibernateTemplate对象,始终都搞不定,望大家指教了。

(顶格的System.out.println()语句均是测试用的语句)

问题补充:
谢谢大家的热心帮助!!

确实其中出了不少问题,主要是最近网上看到解决这个方法的帖子很多,尝试过很多方法,都有点儿改晕了。

一楼的方法我尝试了,还是不行,

Java代码  

  1. private ApplicationContext cxt =  this.getApplicationContext();
  2. private StudentDao studentDao = (StudentDaoHibernate)cxt.getBean("studentDao");

其中那个this.getApplicationContext(); 方法根本不存在啊,无法取得配置文件。

之前类似的方法我也用过就是用

Java代码  

  1. private ApplicationContext cxt =
  2. ew FileSystemXmlApplicationContext("../webapps/JJUFriend/WEB-INF/applicationContext.xml");
  3. private StudentDao studentDao =(StudentDaoHibernate)cxt.getBean("studentDao");

取得,但是当启动服务器后,后台一直跑个不停,仿佛是个死循环似的。浏览器中通过http://localhost:8080访问都无效!

StudentDaoHibernate.java中的private SessionFactory
sessionFactory;已经去掉

数据库方言也该过来了

Spring

2009年11月13日 12:49

天心皓月 
15 
0 0 0

9个答案按时间排序按投票排序

00

采纳的答案

我大至看了一下,个人感觉有两点不对: 
    
    1、StudentManagerImpl.java中的 
      private StudentDao studentDao = new
StudentDaoHibernate() ; 
     不应该new ,直接 = null 就可以。因为你已经使用了spring的注入。

2、StudentDaoHibernate.java中的 
      private SessionFactory sessionFactory;应该去掉。     
     HibernateTemplate ht = this.getHibernateTemplate() ;应该去掉。 
     这两个是父类的属性,不需要你重载,也不该重载。即使你非要重载,那你也应该写上setter吧,要不spring找不到setter不还是会注入到父类中去么,所以你总是获得null。

以上观点仅代表个人意见,如果说的不对,请批评和指正。

2009年11月13日 13:45

fucktianya 

0 0 1

  • 1条评论

00

Java代码  

  1. public class StudentManagerImpl implements StudentManager {
  2. private StudentDao studentDao ;
  3. public static      StudentManagerImpl smi;
  4. public StudentManagerImpl()
  5. {
  6. smi = this;
  7. System.out.println("我自动生成了");
  8. }
  9. 10.
  10. 11.
          public void setStudentDao(StudentDao studentDao){
  11. 12.
              System.out.println("我自动调用了set方法");
  12. 13.
              this.studentDao = studentDao ;
  13. 14.
          }

Java代码  

  1. public class StudentDaoHibernate extends HibernateDaoSupport implements
  2. StudentDao,Serializable {
  3. private SessionFactory sessionFactory;
  4. public static HibernateTemplate ht ;
  5. public static StudentDaoHibernate  sdh;
  6. public StudentDaoHibernate()
  7. {
  8. System.out.println("自动调用");
  9. 10.
      ht = this.getHibernateTemplate();
  10. 11.
      sdh = this;

12.
}

  1. 13.
  2. 14.

通过这两节代码你看看spring在地下偷偷干了啥

StudentManagerImpl.smi 你看看是不是你要的东西

不要直接new

2009年11月13日 17:33

areha001 
51 
0 0 0

  • 添加评论

00

Java代码  

  1. public class StudentManagerImpl implements StudentManager {
  2. private StudentDao studentDao ;
  3. /**
  4. *这个方法是由 spring 自动调用的,只要定义了studentDao ,在类里放上
  5. *getter/setter就不用管了
  6. *    <bean id="mgr"
  7. *         class="com.jjufriend.student.service.impl.StudentManagerImpl">

10.
*         <property name="studentDao" ref="studentDao"></property>

11.
*     </bean>

12.
*   这里的property -name -ref 会帮你做好

  1. 13.
        */
  2. 14.
         public void setStudentDao(StudentDao studentDao){
  3. 15.
  4. 16.
             this.studentDao = studentDao ;
  5. 17.
         }

2009年11月13日 17:24

areha001 
51 
0 0 0

  • 添加评论

00

楼主,两个建议: 
1.仔细对照书籍,按照书上的例子做一遍。你的问题主要是SPRING相关的不熟悉,所以hibernate砍掉,直接spring加载普通的类。先把简单的配置成功,再把hibernate,struts加进来,一个一个来。 
2.出现问题一定要看控制台的信息,错误在哪行,是什么错误。

从你上面的发言可以看出,有些基础的概念还没掌握比如 
ApplicationContext是什么?

你可以通过new 指定xml文件地址,获得spring环境,也可以通过依赖注入,也可以使用getWebApplicationContext(),当然要使用这个需要继承Spring提供的ActionSupport。建议你找本专业点书籍看,SSH的东西,光在问答上还是说不清的。

建议找本实战的书,什么 “深入浅出spring" struts+spring+hibernate集成。

按照书上的例子走一遍。

依赖注入需要为bean的变量提供setter。OVER...

2009年11月13日 16:53

energykey 
919 
0 0 0

  • 添加评论

00

楼主试下一楼的解决方法,个人觉得也是这样

2009年11月13日 16:02

satanest 
137 
0 0 0

  • 添加评论

00

楼主介个配置错误实在是太多了哦~

1楼2楼3楼说的都对~

你按照1楼说的做吧,分给1楼吧.

2009年11月13日 15:57

energykey 
919 
0 0 0

  • 添加评论

00

Java代码  

  1. org.hibernate.dialect.SQLServerDialect

看来也是可以的,整个运行都没问题,没出现楼主说的问题

2009年11月13日 14:25

myali88 
3108 
0 0 0

  • 添加评论

00

Java代码  

  1. <property name="url" value="jdbc:mysql://localhost:3306/jjufriend">

为什么你数据库用的是MySQL,而sessionFactory里的方言设置是

Java代码  

  1. <prop key="hibernate.dialect">
  2. org.hibernate.dialect.SQLServerDialect
  3. </prop>

,用的是SQLServer的,这肯定不行吧?!

2009年11月13日 14:04

myali88 
3108 
0 0 0

  • 添加评论

00

Java代码  

  1. private ApplicationContext cxt =  this.getApplicationContext();
  2. private StudentDao studentDao = (StudentDaoHibernate)cxt.getBean("studentDao");

studentDao 对象直接 new 的话里面是没有Hibernate上下文的。 
只能取得在配置文件中自动生成的实例

getHibernateTemplate()为NUll的更多相关文章

  1. 《深入理解JAVA虚拟机》笔记1

    java程序运行时的内存空间,按照虚拟机规范有下面几项: )程序计数器 指示下条命令执行地址.当然是线程私有,不然线程怎么能并行的起来. 不重要,占内存很小,忽略不计. )方法区 这个名字很让我迷惑. ...

  2. 【转】getHibernateTemplate出现的所有find方法的总结

    一.find(String queryString); 示例:this.getHibernateTemplate().find("from bean.User"); 返回所有Use ...

  3. getHibernateTemplate().find()

    find(String queryString, Object[] values); 这个方法后者的参数必须是一个数组,而不能是一个List. List ul=getHibernateTemplate ...

  4. getHibernateTemplate()

    getHibernateTemplate 前提条件:你的类必须继承HibernateDaoSupport 一: 回调函数: public List getList(){   return (List ...

  5. hql Hibernate.gethibernatetemplate()

    1. find(String hql);  //普通查询 示例:this.gethibernateTemplate().find("from User"); 2. find(Str ...

  6. [转]getHibernateTemplate出现的所有find方法的总结

    一.find(String queryString); 示例:this.getHibernateTemplate().find("from bean.User"); 返回所有Use ...

  7. hibernate中 criteria.setProjection(Projections.rowCount()).uniqueResult()为null的Bug

    在hibernate中,在查询总数时,会使用如下方法; public Integer getCount(final DetachedCriteria detachedCriteria) {       ...

  8. 关于HibernateDaoSupport中的getHibernateTemplate().execute及executeFind方法

    转自:https://blog.csdn.net/angus_17/article/details/8501668 1. 这两个方法都是为了Spring在接管Hibernate之后,可以对Hibern ...

  9. Hibernate hql getHibernateTemplate()常用方法汇总

    转自:https://www.iteye.com/blog/zwdsmileface-2191943 getHibernateTemplate()常用方法 一.find(String queryStr ...

随机推荐

  1. CTG

     服务端:一.修改IP地址AIX上CICS REGION的目录/var/cics_regions/your_region_name/database/LD二.修改文件LD.stanza中的IP地址三. ...

  2. MySQL 5.7 Zip 安装(win7)

    参考官方文档 http://dev.mysql.com/doc/refman/5.7/en/windows-install-archive.html 2.3.5.1 Extracting the In ...

  3. Typical sentences in SCI papers

       Beginning  1. In this paper, we focus on the need for   2. This paper proceeds as follow.   3. Th ...

  4. 如何在java类中读取Properties配置文件

    在com.example包下有一个test.properties文件和测试类PropertyReadTest.java. test.properties 文件内容: author=zeige  tea ...

  5. mina socket底层主流程源码实现

    一,mina的架构 mina 架构可以大致分为三部分,ioService ,ioFilterChain , IoHandler   ioService:用于接受服务或者连接服务,例如socket 接收 ...

  6. [精校版]The Swift Programming Language

    通常来说,编程语言教程中的第一个程序应该在屏幕上打印“Hello, world”.在 Swift 中,可以用一行代码实现:  println("hello, world")   如 ...

  7. Android:通过startActivityForResult方法来得到Activity的回传值

    在一些情况下,我们通过 A activity跳转到 B activity上,这时希望 A activtiy能从 B activity上得到一些返回值,这个时候我们就不能使用startActivity方 ...

  8. WebApp

    目前的手机APP有三类:原生APP,WebAPP,HybridApp:HybridApp结合了前两类APP各自的优点,越来越流行. Hybrid App的兴起是现阶段移动互联网产业的一种偶然.移动互联 ...

  9. SQL效率的几点心得

    这几天一直在写SQL,有时候对比同样效果的SQL语句,可是查询所需要的时间有时候相差很多,下面总结遇到的几个点: 1.between   and 在有些时候自己比较喜欢使用这个语句,因为可以通过把数据 ...

  10. VirtualBox虚拟机安装MSDOS和MINIX2.0.0双系统

    1. 在VirtualBox中新建一个MSDOS虚拟机. 2.下载一个MSDOS软盘镜像. 3.启动虚拟机,提示选择安装盘时,选择步骤2下载过来的MSDOS镜像. 4.正常启动进入DOS命令行,用FD ...