dingvictory 2009-11-13 12:49
浏览 422
已采纳

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

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

[size=large][b]applicationContext.xml:([/b]事务处理这儿没贴出来)[/size]
[code="java"]
<?xml version="1.0" encoding="UTF-8"?>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">

<!-- 定义数据源 -->

class="org.apache.commons.dbcp.BasicDataSource">
value="com.mysql.jdbc.Driver">




<!-- 定义Hibernate的sessionFactory -->   
<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource">
        <ref bean="dataSource" />
    </property>

    <!-- Hibernate  的sessionFactory的属性 -->

    <property name="hibernateProperties">       
        <props>
            <!-- 数据库方言 -->
            <prop key="hibernate.dialect">
                org.hibernate.dialect.SQLServerDialect
            </prop>
            <!-- 显示Hibernate持久化操作所生成的SQL语句 -->
            <prop key="hibernate.show_sql">true</prop>
            <!-- 将SQL脚本进行格式化后再输出 -->
            <prop key="hibernate.format_sql">true</prop>            
        </props>
    </property>
    <!-- 列出全部的映射文件 -->
    <property name="mappingResources">
        <list>                      
            <value>com/jjufriend/student/model/Student.hbm.xml</value></list>
    </property></bean>

<!-- 配置dao组件 -->
<bean id="studentDao"
    class="com.jjufriend.student.dao.impl.StudentDaoHibernate">
    <!-- 依赖注入DAO组件所必需的SessionFactory引用 -->
    <property name="sessionFactory" ref="sessionFactory">
    </property>
</bean>
<!-- 配置业务逻辑组件 -->
<bean id="mgr"
    class="com.jjufriend.student.service.impl.StudentManagerImpl">
    <property name="studentDao" ref="studentDao"></property>
</bean>
[/code]

[size=large]studentDao.java:[/size]
[code="java"]package com.jjufriend.student.dao;

import java.util.List;

import com.jjufriend.student.model.Student;

public interface StudentDao {

Student get(Integer id);

Integer save(Student student);

void update(Student student);

void delete(Student student);

void delete(Integer id);

List<Student> findAll();

Student findStudentByNameAndPass(String username,String password);

Student findByName(String username);

}[/code]

[size=large]StudentDaoHibernate.java:[/size]
[code="java"]package com.jjufriend.student.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.jjufriend.student.dao.StudentDao;
import com.jjufriend.student.model.Student;

public class StudentDaoHibernate extends HibernateDaoSupport implements
StudentDao,Serializable {
private SessionFactory sessionFactory;

HibernateTemplate ht = this.getHibernateTemplate() ;

public void delete(Student student) {
    // TODO Auto-generated method stub
    getHibernateTemplate().delete(student);

}

public void delete(Integer id) {
    // TODO Auto-generated method stub
    getHibernateTemplate().delete(get(id));

}

public List<Student> findAll() {
    // TODO Auto-generated method stub
    return (List<Student>)getHibernateTemplate().find("from Student");

}

public Student findByName(String username) {

    List stu =  getHibernateTemplate().find("from Student st where st.username = ?",username);

    if(stu != null && stu.size() >= 1){
        return (Student)stu.get(0);
    }

    return null;
}

public Student findStudentByNameAndPass(String username, String password) {
    // TODO Auto-generated method stub
    List students = null;
    try{

    //  HibernateTemplate temple = this.getHibernateTemplate();

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

// 取出所有 students = temple.find("from student");
students = ht.find("from student st where st.username = " + username + " and st.password = " + password);

    }catch(Exception  e){
        System.out.println("查找过程中出现异常..............");
        e.printStackTrace();
    }
    if(students != null && students.size() >= 1){
        return (Student)students.get(0);
        }
    return null;
}

public Student get(Integer id) {

    return (Student)getHibernateTemplate().get(Student.class, id);

}

public Integer save(Student student) {
    return (Integer)getHibernateTemplate().save(student);
}

public void update(Student student) {
    // TODO Auto-generated method stub
    getHibernateTemplate().update(student);

}

}
[/code]
[size=large]StudentManager.java:[/size]
[code="java"]package com.jjufriend.student.service;

import com.jjufriend.student.model.Student;

public interface StudentManager {

int addStudent(Student student) throws Exception;

int loginValid(Student student) throws Exception;

boolean validateName(String username) throws Exception;

}
[/code]

[size=large]StudentManagerImpl.java:[/size]
[code="java"]package com.jjufriend.student.service.impl;

import com.jjufriend.student.dao.StudentDao;
import com.jjufriend.student.dao.impl.StudentDaoHibernate;
import com.jjufriend.student.model.Student;
import com.jjufriend.student.service.StudentManager;

public class StudentManagerImpl implements StudentManager {
/*2009-11-12 22:44修改 出去new StudentDaoHibernate() */
private StudentDao studentDao = new StudentDaoHibernate() ;

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

public void setStudentDao(StudentDao studentDao){

    this.studentDao = studentDao ;
}


public int addStudent(Student student) throws Exception {
    // TODO Auto-generated method stub
    try{
        studentDao.save(student);
        return student.getId();

    }catch(Exception e){
        e.printStackTrace();
        throw new Exception("新增用户时出现异常");
    }

}

public int loginValid(Student student) throws Exception {
    try{

System.out.println(studentDao);
System.out.println("是否取到页面提交的数据:Name="+student.getUsername());
Student stu = studentDao.findStudentByNameAndPass(student.getUsername(), student.getPassword());
if(stu != null ){
return stu.getId();
}

    }catch(Exception e){        
        System.out.println("验证用户登录时出现异常");
        e.printStackTrace();
    }

    // TODO Auto-generated method stub
    return -1;
}

public boolean validateName(String username) throws Exception {
    // TODO Auto-generated method stub
    try{
        if (studentDao.findByName(username) != null){
            return true ;
        }


    }catch(Exception e){
        System.out.println("验证用户名是否用效时出错");
        e.printStackTrace();

    }
    return false ; 

}

}
[/code]

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

下面这种方法是说不能直接new StudentDao对象,用下面这种方法取得,可以启动服务器老是不停地跳动,一直不停,直到报错。
[code="java"]
// private ApplicationContext cxt =
// new FileSystemXmlApplicationContext("../webapps/JJUFriend/WEB-INF/applicationContext.xml");
// private StudentDao studentDao =(StudentDaoHibernate)cxt.getBean("studentDao");[/code]

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

[size=medium](顶格的System.out.println()语句均是测试用的语句)[/size]

[b]问题补充:[/b]
谢谢大家的热心帮助!!

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

一楼的方法我尝试了,还是不行,[code="java"]
private ApplicationContext cxt = this.getApplicationContext();

private StudentDao studentDao = (StudentDaoHibernate)cxt.getBean("studentDao"); [/code]
其中那个this.getApplicationContext(); 方法根本不存在啊,无法取得配置文件。

之前类似的方法我也用过就是用[code="java"] private ApplicationContext cxt =

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

private StudentDao studentDao =(StudentDaoHibernate)cxt.getBean("studentDao"); [/code]取得,但是当启动服务器后,后台一直跑个不停,仿佛是个死循环似的。浏览器中通过http://localhost:8080访问都无效!

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

数据库方言也该过来了

  • 写回答

9条回答 默认 最新

  • flybar0015 2009-11-13 13:45
    关注

    我大至看了一下,个人感觉有两点不对:

    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。
    
    以上观点仅代表个人意见,如果说的不对,请批评和指正。
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(8条)

报告相同问题?

悬赏问题

  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B
  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿