- 错误原因:getHibernateTemplate()为空,用DAO的findById()方法时就出抛出空指针异常,原因在于在Struts2 action里手动实例化了DAO对象。
- 错误分析:Struts2.1 + Spring2.5.6 + Hibernate 3.3 整合,整合后struts2动作委托给Spring来管理,DAO对象的创建也由spring来负责,如下DAO的导入包的部分
package com.jiyi.dao; import java.util.List; import org.hibernate.LockMode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.jiyi.model.Rollpictures;
一方面,DAO对象由Spring来维护及创建,所以要遵循依赖注入的原则来降低偶合度。
另一方面,下面的HibernateDaoSupport告诉我们,Spring在创建Dao对象的同时还偷偷地为HibernateDaoSupport注入了SessionFacetory,而SessionFacetory对Hibernate的重要性是不言而喻的。它负责管理我们的session对象,session的一次会话可以认为是对数据库的一次操作。
1/* * Copyright 2002-2007 the original author or authors. *Licensed under the Apache License, Version 2.0 (the "License"); *you may not use this file except in compliance with the License. *You may obtain a copy of the License at *http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.orm.hibernate.support; import net.sf.hibernate.HibernateException; import net.sf.hibernate.Session; import net.sf.hibernate.SessionFactory; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.dao.support.DaoSupport; import org.springframework.orm.hibernate.HibernateTemplate; import org.springframework.orm.hibernate.SessionFactoryUtils; /** * Convenient super class for Hibernate-based data access objects. * * <p>Requires a {@link net.sf.hibernate.SessionFactory} to be set, providing a * {@link org.springframework.orm.hibernate.HibernateTemplate} based on it to * subclasses through the {@link #getHibernateTemplate()} method. * Can alternatively be initialized directly with a HibernateTemplate, * in order to reuse the latter's settings such as the SessionFactory, * exception translator, flush mode, etc. * * <p>This base class is mainly intended for HibernateTemplate usage but can * also be used when working with a Hibernate Session directly, for example * when relying on transactional Sessions. Convenience {@link #getSession} * and {@link #releaseSession} methods are provided for that usage style. * * <p>This class will create its own HibernateTemplate instance if a SessionFactory * is passed in. The "allowCreate" flag on that HibernateTemplate will be "true" * by default. A custom HibernateTemplate instance can be used through overriding * {@link #createHibernateTemplate}. * * @author Juergen Hoeller * @since 28.07.2003 * @see #setSessionFactory * @see #getHibernateTemplate * @see org.springframework.orm.hibernate.HibernateTemplate */ public abstract class HibernateDaoSupport extends DaoSupport { private HibernateTemplate hibernateTemplate; /** * Set the Hibernate SessionFactory to be used by this DAO. * Will automatically create a HibernateTemplate for the given SessionFactory. * @see #createHibernateTemplate * @see #setHibernateTemplate */ public final void setSessionFactory(SessionFactory sessionFactory) { this.hibernateTemplate = createHibernateTemplate(sessionFactory); } /** * Create a HibernateTemplate for the given SessionFactory. * Only invoked if populating the DAO with a SessionFactory reference! * <p>Can be overridden in subclasses to provide a HibernateTemplate instance * with different configuration, or a custom HibernateTemplate subclass. * @param sessionFactory the Hibernate SessionFactory to create a HibernateTemplate for * @return the new HibernateTemplate instance * @see #setSessionFactory */ protected HibernateTemplate createHibernateTemplate(SessionFactory sessionFactory) { return new HibernateTemplate(sessionFactory); } /** * Return the Hibernate SessionFactory used by this DAO. */ public final SessionFactory getSessionFactory() { return (this.hibernateTemplate != null ? this.hibernateTemplate.getSessionFactory() : null); } /** * Set the HibernateTemplate for this DAO explicitly, * as an alternative to specifying a SessionFactory. * @see #setSessionFactory */ public final void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } /** * Return the HibernateTemplate for this DAO, * pre-initialized with the SessionFactory or set explicitly. * <p><b>Note: The returned HibernateTemplate is a shared instance.</b> * You may introspect its configuration, but not modify the configuration * (other than from within an {@link #initDao} implementation). * Consider creating a custom HibernateTemplate instance via * <code>new HibernateTemplate(getSessionFactory())</code>, in which * case you're allowed to customize the settings on the resulting instance. */ public final HibernateTemplate getHibernateTemplate() { return this.hibernateTemplate; } protected final void checkDaoConfig() { if (this.hibernateTemplate == null) { throw new IllegalArgumentException ("'sessionFactory' or 'hibernateTemplate' is required"); } } /** * Obtain a Hibernate Session, either from the current transaction or * a new one. The latter is only allowed if the * {@link org.springframework.orm.hibernate.HibernateTemplate#setAllowCreate "allowCreate"} * setting of this bean's {@link #setHibernateTemplate HibernateTemplate} is "true". * <p><b>Note that this is not meant to be invoked from HibernateTemplate code * but rather just in plain Hibernate code.</b> Either rely on a thread-bound * Session or use it in combination with {@link #releaseSession}. * <p>In general, it is recommended to use HibernateTemplate, either with * the provided convenience operations or with a custom HibernateCallback * that provides you with a Session to work on. HibernateTemplate will care * for all resource management and for proper exception conversion. * @return the Hibernate Session * @throws DataAccessResourceFailureException if the Session couldn't be created * @throws IllegalStateException if no thread-bound Session found and allowCreate=false * @see org.springframework.orm.hibernate.SessionFactoryUtils#getSession(SessionFactory, boolean) */ protected final Session getSession() throws DataAccessResourceFailureException, IllegalStateException { return getSession(this.hibernateTemplate.isAllowCreate()); } /** * Obtain a Hibernate Session, either from the current transaction or * a new one. The latter is only allowed if "allowCreate" is true. * <p><b>Note that this is not meant to be invoked from HibernateTemplate code * but rather just in plain Hibernate code.</b> Either rely on a thread-bound * Session or use it in combination with {@link #releaseSession}. * <p>In general, it is recommended to use * {@link #getHibernateTemplate() HibernateTemplate}, either with * the provided convenience operations or with a custom * {@link org.springframework.orm.hibernate.HibernateCallback} that * provides you with a Session to work on. HibernateTemplate will care * for all resource management and for proper exception conversion. * @param allowCreate if a non-transactional Session should be created when no * transactional Session can be found for the current thread * @return the Hibernate Session * @throws DataAccessResourceFailureException if the Session couldn't be created * @throws IllegalStateException if no thread-bound Session found and allowCreate=false * @see org.springframework.orm.hibernate.SessionFactoryUtils#getSession(SessionFactory, boolean) */ protected final Session getSession(boolean allowCreate) throws DataAccessResourceFailureException, IllegalStateException { return (!allowCreate ? SessionFactoryUtils.getSession(getSessionFactory(), false) : SessionFactoryUtils.getSession( getSessionFactory(), this.hibernateTemplate.getEntityInterceptor(), this.hibernateTemplate.getJdbcExceptionTranslator())); } /** * Convert the given HibernateException to an appropriate exception from the * <code>org.springframework.dao</code> hierarchy. Will automatically detect * wrapped SQLExceptions and convert them accordingly. * <p>Delegates to the * {@link org.springframework.orm.hibernate.HibernateTemplate#convertHibernateAccessException} * method of this DAO's HibernateTemplate. * <p>Typically used in plain Hibernate code, in combination with * {@link #getSession} and {@link #releaseSession}. * @param ex HibernateException that occured * @return the corresponding DataAccessException instance * @see org.springframework.orm.hibernate.HibernateTemplate#convertHibernateAccessException */ protected final DataAccessException convertHibernateAccessException(HibernateException ex) { return this.hibernateTemplate.convertHibernateAccessException(ex); } /** * Close the given Hibernate Session, created via this DAO's SessionFactory, * if it isn't bound to the thread (i.e. isn't a transactional Session). * <p>Typically used in plain Hibernate code, in combination with * {@link #getSession} and {@link #convertHibernateAccessException}. * @param session the Session to close * @see org.springframework.orm.hibernate.SessionFactoryUtils#releaseSession */ protected final void releaseSession(Session session) { SessionFactoryUtils.releaseSession(session, getSessionFactory()); } }
- 解决方法:以注入的方式实例化DAO对象。
相关推荐
SRAM:SRAM入门指南与工作原理
SRAM(Static Random Access Memory),即静态随机存取存储器,是一种能够读取和写入数据的内存(RAM)。它使用由晶体管组成的触发器来存储数据,只要有电源供应,数据就可以稳定地保存。与动态随机存取存储器(DRAM)不同,SRAM 不需要周期性地刷新来保持数据。
使用getHibernateTemplate()的方法时出现空指针异常的解决办法
真是无力吐槽网上d
电力-平衡式IEC 60870-5-101规约报文解析
本文详细介绍了电力自动化中平衡式IEC 60870-5-101规约的应用,包括链路建立与初始化、对时、遥控操作、数据上送和总召唤等关键步骤,通过实例解析了报文格式和交互过程,是理解配网自动化通信的重要参考资料。
spring getHibernateTemplate() 返回null的问题
public class BasicDAOImpl extends HibernateDaoSupport implements BasicDAO{ public List findByHql(String hql)throws DataAccessException{ System.out.println("1111111111111"+getHi...
保姆级教程:用OSSH免费版+FreeRADIUS+FreeAC NAC,从零搭建一套企业级无线Portal认证系统
本文提供了一套基于OSSH免费版、FreeRADIUS和FreeAC NAC的企业级无线Portal认证系统搭建教程。从环境规划、核心组件安装到认证策略与用户管理,详细介绍了如何利用开源工具构建高效、安全的认证体系,特别适用于预算有限但需求严格的企业场景。
JS逆向-B站评论数据w_rid参数和wts参数
本文是该专栏的第69篇,后面会持续分享python爬虫干货知识。本文以B站的评论数据为例,通过JS逆向获取其中的w_rid参数以及wts参数生成规律。具体的“逆向”思路逻辑,笔者将会详细介绍每个步骤,并且将在正文结合“完整代码”来详细介绍。废话不多说,具体细节部分以及详细思路逻辑,笔者将在正文结合完整代码进行详细说明。(附带完整代码)
SSH组合,中this.getHibernateTemplate().getSessionFactory().openSession()报空指针错误
其中Dao中的那些方法都是使用MyEclips中Hibernate组件自动生成的。 当我在service里写过几个方法,其中别的方法使用都正常,只有一个出了毛病,追踪问题到最后查找到是Hibernate里某个方法的Session session = this.getHibernateTemplate().getSessionFactory().openSession();报空指针错
以 Cloud 为核心的设备 mTLS 证书体系:从产品需求到 OP-TEE 安全落地
本文探讨了以云端为核心的物联网设备mTLS证书体系构建方案。文章从产品需求出发,分析了云端必须采用mTLS+证书体系管理设备身份的原因,指出静态Token方案的三大缺陷:身份不可控、运营不可控和审计不可控。重点阐述了mTLS在产品中的核心功能是加密传输和双向认证,并详细列出了云端PKI、设备注册中心等必备组件。在设备侧,强调必须通过OP-TEE技术保护私钥安全,提出了一个包含密钥生成、CSR导出等功能的TA设计方案。最后,文章给出了云端端到端流程示例,说明如何将证书生命周期管理转化为可运营的产品能力,包括自
解决this.getHibernateTemplate()的空指针异常的问题
刚刚在整合SSH时碰到了这样一个问题: 当我用junit测试时不会报任何异常,数据也都能得到 public class BuyerTest { @BeforeClass public static void begin() throws Exception{}@Test public void save(){ Configuration config=new AnnotationCo
【数据集实例】CMIP6气候模式数据下载-以河东地区为例
以河东地区为例,介绍CMIP6数据下载及处理
华为OD机试 - 项目规划 - 深度优先搜索dfs(Java 2024 C卷 100分)
每一题都有详细的答题思路、详细的代码注释、样例测试,发现新题目,随时更新,全天优快云在线答疑。
整合SSH时遇到getHibernateTemplate()为null的问题
UserDaoImpl类 public class UserDaoImpl extends HibernateDaoSupport implements UserDao{ @Override public User findByNameAndPassword(String username, String password) { System...
《网络安全自学教程》- Windows基线检查加固
Windows安全配置,基线检查标准,基线加固方式
SSH框架搭建getHibernateTemplate()空指针解决办法
1、问题的出现: 当hibernate的事务管理、业务逻辑接口、action等都交给spring管理时: 容易出现getHibernateTemplate()或getSession()等空指针问题,或其他情况。 2、解决办法: 1)检查applicationContext的配置是否有错误,serviceImpl、sessionFactory、dao等是否都注入正确; 2)检查action
NTscan扫描工具
ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。
SIMATIC S7-1200, S7-1500 PID 控制[手册]
SIMATIC S7-1200, S7-1500 PID 控制[手册]
ssh2项目中getHibernateTemplate().find常见错误小结
其hql与普通sql语句有不少差别。 实际上,作为面向对象工具,代码部分不必考虑实际表本身。这句话自己多实践几次就能真正体会出来。 一: /* *正确用法 */ String hql="select g.goodsid,g.goodsname Goods g where g.goodstype = ?"; /* *错误用法1
Probability and Statistics - 4th edition
Probability and Statistics - 4th edition
hibernate使用getHibernateTemplate().update()出错
参考文章:hibernate使用getHibernateTemplate().update()出错 在使用SSH框架时候,使用getHibernateTemplate().update() 更新数据出现 java.sql.BatchUpdateException: You have an error in your SQL syntax; check the manual that
gethibernatetemplate的find方法
为什么使用gethibernatetemplate的find方法 ? 一般我们 访问数据库 有两种选择 : getSession().createQuery("from Area"); getHibernateTemplate().find( "FROM Area); 通过测试: 分别循环调用getSession().createQuery("fromUsers
ssh框架整合的时候出现Unable to load configuration问题、getHibernateTemplate().save空指针
在ssh框架搭建的时候整合的时候出现这个错误的原因是,少了一个jar包。 加入jar包struts2-spring-plugin-2.2.3.1.jar 在使用getHibernateTemplate().save的时候出现空指针。 原因是因为spring的注入机制,使用Spring注入 就不能直接用new了。
getHibernateTemplate()为NUll
getHibernateTemplate()为NUll,困扰好几天了,网上也找了好些方法一直解决不掉15 小弟刚刚开始学SSH,是用的Struts2+Hibernate+Spring,运行的时候发现getHibernateTemplate()得到的模板类始终是nUll值,郁闷好几天了,一直在我网上试各种方法,迄今任为解决,恳请各位指教咯! applicationContex...
SSH整合执行getHibernateTemplate().delete()如果删除的东西不存在而报错的解决方法
UserDaoImpl的代码 @Override public void delete(User user) { // TODO 自动生成的方法存根 this.getHibernateTemplate().delete(user); } 原本UserAction 的代码 public String delete(){ this.userService.delete...
DAO中调用getHibernateTemplate()方法时就是报空指向异常
在整合ssh框架时,碰到这个问题,困扰了好几天 在网上看了很多资料,很多问题,出现的方式不同 但究其原因是没有从ApplicationContext中获取对象 当你自己用 StuDAO sd = new StuDAO() ( 其实我并没有用这样的方式获取对象,而是在配置文件中配置了sessionFactory属性 但是在DAO中调用getHibernateTem
解决this.getHibernateTemplate().save();报空指针异常问题
接上篇博文 刚刚在整合SSH时碰到了这样一个问题: 代码如下 package com.crm.biz;import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import org.springframework.stereotype.Service; import org.springframe
getHibernateTemplate().saveOrUpdate 不执行
在ssh中使用hibernateTemplate来保存对象的时候,出现一个问题,就是saveOrUpdate既不报错,也不在控制台打印插入语句,也不想数据库插入数据。 问题解决: 这个是事务的原因,检查事务的配置是否与使用的包名对应的上 com.ggyan.pes.login.service.*.*(..))"/>
Struts Hibernate Spring SSH集成碰到的问题
参考资料: 1,三种整合 Struts 应用程序与 Spring 的方式 http://www.ibm.com/developerworks/cn/java/j-sr2.html SSH集成碰到的问题1. getHibernateTemplate() 方法返回 NULL 值
SSH实现删除功能的一些问题
整合完SSH实现增删改查功能的时候,遇到一些问题: 当我通过页面id实现删除功能的时候,第次都必须点击两次删除链接,才能将一条记录删除掉,于是我在代码中添加输出语句,看看能不能取到id,结果发现点击第一次,id的值是0,点击第二次的时候,id的值变成了当前记录的id,然后,把这条记录删除掉了。 在网上找了解决办法,我把原来的getSession().delete(user)换成getHiber
SSH 集成项目中geTemplate().save(Object obj)方法不能保存数据且没有sql语句输出
SSH 集成项目中getHibernateTemplate().save(Object obj)方法保存数据
1万+



被折叠的 条评论
为什么被折叠?



