关于Spring的LocalSessionFactoryBean的问题

问题描述

做了一个spring+hibernate的例子xml是这样的<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"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.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--SessionFactory Transaction******************************************--><bean id="sessionFactory"class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"><property name="configLocation"value="classpath:hibernate.cfg.xml"></property></bean><bean id="transactionManager"class="org.springframework.orm.hibernate3.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory" /></bean><tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes><tx:method name="initial*" propagation="REQUIRED" /><tx:method name="add*" propagation="REQUIRED" /><tx:method name="update*" propagation="REQUIRED" /><tx:method name="delete*" propagation="REQUIRED" /><tx:method name="*" propagation="SUPPORTS" read-only="true" /></tx:attributes></tx:advice><aop:config><aop:advisor pointcut="execution(* com.service.*Service.*(..))"advice-ref="txAdvice" /></aop:config> <!--SessionFactory Transaction End**************************************--><!--DAO Begin***********************************************************--><bean id="productDAO" class="com.dao.ProductDAO"><property name="sessionFactory" ref="sessionFactory"></property></bean><bean id="categoryDAO" class="com.dao.CategoryDAO"><property name="sessionFactory" ref="sessionFactory"></property></bean><!--DAO End*************************************************************--><!--Service*************************************************************--><bean id="initialService" class="com.service.InitialServiceImpl"><property name="categoryDAO" ref="categoryDAO"></property><property name="productDAO" ref="productDAO"></property></bean><!--Service End*********************************************************--></beans>ProductDAO的代码:package com.dao;import java.util.List;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.hibernate.LockMode;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.criterion.Example;import com.domain.Product;public class ProductDAO {private static final Log log = LogFactory.getLog(ProductDAO.class);// property constantspublic static final String NAME = "name";public static final String DESCRIPTION = "description";public static final String PRICE = "price";/***************************************************************** */private SessionFactory sessionFactory;public void setSessionFactory(SessionFactory sessionFactory) {this.sessionFactory = sessionFactory;}private Session getSession() {return sessionFactory.getCurrentSession();}/***************************************************************** */public void save(Product transientInstance) {log.debug("saving Product instance");try {getSession().save(transientInstance);log.debug("save successful");} catch (RuntimeException re) {log.error("save failed", re);throw re;}}public void delete(Product persistentInstance) {log.debug("deleting Product instance");try {getSession().delete(persistentInstance);log.debug("delete successful");} catch (RuntimeException re) {log.error("delete failed", re);throw re;}}public Product findById(java.lang.Integer id) {log.debug("getting Product instance with id: " + id);try {Product instance = (Product) getSession().get("com.domain.Product",id);return instance;} catch (RuntimeException re) {log.error("get failed", re);throw re;}}@SuppressWarnings("unchecked")public List<Product> findByExample(Product instance) {log.debug("finding Product instance by example");try {List<Product> results = getSession().createCriteria("com.domain.Product").add(Example.create(instance)).list();log.debug("find by example successful, result size: "+ results.size());return results;} catch (RuntimeException re) {log.error("find by example failed", re);throw re;}}@SuppressWarnings("unchecked")public List<Product> findByProperty(String propertyName, Object value) {log.debug("finding Product instance with property: " + propertyName+ ", value: " + value);try {String queryString = "from Product as model where model."+ propertyName + "= ?";Query queryObject = getSession().createQuery(queryString);queryObject.setParameter(0, value);return queryObject.list();} catch (RuntimeException re) {log.error("find by property name failed", re);throw re;}}public List<Product> findByName(Object name) {return findByProperty(NAME, name);}public List<Product> findByDescription(Object description) {return findByProperty(DESCRIPTION, description);}public List<Product> findByPrice(Object price) {return findByProperty(PRICE, price);}@SuppressWarnings("unchecked")public List<Product> findAll() {log.debug("finding all Product instances");try {String queryString = "from Product";Query queryObject = getSession().createQuery(queryString);return queryObject.list();} catch (RuntimeException re) {log.error("find all failed", re);throw re;}}public Product merge(Product detachedInstance) {log.debug("merging Product instance");try {Product result = (Product) getSession().merge(detachedInstance);log.debug("merge successful");return result;} catch (RuntimeException re) {log.error("merge failed", re);throw re;}}public void attachDirty(Product instance) {log.debug("attaching dirty Product instance");try {getSession().saveOrUpdate(instance);log.debug("attach successful");} catch (RuntimeException re) {log.error("attach failed", re);throw re;}}public void attachClean(Product instance) {log.debug("attaching clean Product instance");try {getSession().lock(instance, LockMode.NONE);log.debug("attach successful");} catch (RuntimeException re) {log.error("attach failed", re);throw re;}}}问题是xml文件中Spring给productDAO注入的bean类型明明是org.springframework.orm.hibernate3.LocalSessionFactoryBean;这个类型根本没有getCurrentSession的方法。而productDAO中的sessionFactory是org.hibernate.SessionFactory,这中间的类型是怎么转换的啊?试了一下往数据库保存是成功的,就是想不通这个类型的转换,我看LocalSessionFactoryBean也没有实现SessionFactory这个接口啊?难道是LocalSessionFactoryBean的getObject()方法?

解决方案

引用难道是LocalSessionFactoryBean的getObject()方法? 正是如此!LocalSessionFactoryBean实现了org.springframework.beans.factory.FactoryBean接口, spring在装配的时候, 如果发现实现了org.springframework.beans.factory.FactoryBean接口, 就会使用FactoryBean#getObject() 方法返回的对象装配,具体的可以看下文档.如果你想拿到LocalSessionFactoryBean实例, 在id前面加个'&'就可以了,在你的配置文件中BeanFactory.getBean('&sessionFactory')拿到的就是LocalSessionFactoryBean的实例.
解决方案二:
楼上说的非常正确,这就是要搞清BeanFactory和FactoryBean的区别

时间: 2024-08-04 03:34:58

关于Spring的LocalSessionFactoryBean的问题的相关文章

《Spring 5 官方文档》16.ORM和数据访问(一)

16.1介绍一下Spring中的ORM Spring框架在实现资源管理.数据访问对象(DAO)层,和事务策略等方面,支持对Java持久化API(JPA)以及原生Hibernate的集成.以Hibernate举例来说,Spring有非常赞的IoC功能,可以解决许多典型的Hibernate配置和集成问题.开发者可以通过依赖注入来配置O-R(对象关系)映射组件支持的特性.Hibernate的这些特性可以参与Spring的资源和事务管理,并且符合Spring的通用事务和DAO层的异常体系.因此,Spri

jdbc-jdbcTemplate-hibernate-jpa-springDataJpa系列(一)

1 需要解决的疑惑 目前jdbc.jdbcTemplate.hibernate.jpa.spring之间有或多或少的关系.在使用它们的时候有着各种各样的配置,初学者很容易分不清到底各自都做了什么事情,如果对自己要求高点,那就测试下下面几个问题: jdbc的几个主要对象是什么? jdbc的原生方式是什么样的?怎么配置?怎么使用事务? jdbcTemplate又是如何封装jdbc的?怎么使用事务? hibernate的几个主要对象是什么? hibernate的原生xml方式是什么样的?注解方式是什么

s2sh框架搭建(基于spring aop)

对于spring aop 是如何管理事务的,请看一下:http://bbs.csdn.net/topics/290021423 1.applicationContext.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3

Spring 编程入门十大问题解答

编程|解答|问题 1.如何学习Spring? 你可以通过下列途径学习spring: (1) spring下载包中doc目录下的MVC-step-by-step和sample目录下的例子都是比较好的spring开发的例子. (2) AppFuse集成了目前最流行的几个开源轻量级框架或者工具 Ant,XDoclet,Spring,Hibernate(iBATIS),JUnit,Cactus,StrutsTestCase,Canoo's WebTest,Struts Menu,Display Tag

POJO应用架构:Spring与EJB 3.0的对比

架构 爱因斯坦曾经说过:"每件事物都应该尽可能简单,而不是更简单".的确,对科学真理的追求都是为了简化理论的根本假设,这样我们才能处理真正麻烦的问题.企业级软件的开发也是这样的. 简化企业级软件开发的关键是提供一个隐藏了复杂性(例如事务.安全性和永续性)的应用框架.良好设计的框架组件可以提升代码的重复使用(reuse)能力,提高开发效率,从而得到更好的软件质量.但是,目前J2EE 1.4中的EJB 2.1框架组件被人们普遍认为是设计较差的和过于复杂的.Java开发者对EJB 2.1很不

Struts+Spring+Hibernate实现上传下载

上传|下载 引言 文件的上传和下载在J2EE编程已经是一个非常古老的话题了,也许您马上就能掰着指头数出好几个著名的大件:如SmartUpload.Apache的FileUpload.但如果您的项目是构建在Struts+Spring+Hibernate(以下称SSH)框架上的,这些大件就显得笨重而沧桑了,SSH提供了一个简捷方便的文件上传下载的方案,我们只需要通过一些配置并辅以少量的代码就可以完好解决这个问题了. 本文将围绕SSH文件上传下载的主题,向您详细讲述如何开发基于SSH的Web程序.SS

Struts+Spring+Hibernate组装web应用

web 摘要: 这篇文章将讨论怎样组合几个著名的框架去做到松耦合的目的,怎样建立你的构架,怎样让你的各个应用层保持一致.富于挑战的是:组合这些框架使得每一层都以一种松耦合的方式彼此沟通,而与底层的技术无关.这篇文章将使用3种流行的开源框架来讨论组合框架的策略 其实,就算用Java建造一个不是很烦琐的web应用程序,也不是件轻松的事情.当为一个应用程序建造一个构架时有许多事情需要考虑.从高层来说,开发者需要考虑:怎样建立用户接口?在哪里处理业务逻辑?和怎样持久化应用数据.这三层每一层都有它们各自的

使用Hibernate 和 Spring 实现一个事务持久层

1.首先实现一个接口. ============================================================ package com.cqtele.tnbos;import java.util.*;public interface IUserDao { public void insertUser(userInfo user); public List findUser(String sql);} ===============================

JSF+Spring+Hibernate的实例讲解

js 使用JavaServer Faces(JSF).Spring Framework和Hibernate建立一个真实的Web应用程序内容概要使用JSF建立一个真实的Web应用程序不是没有意义的任务,这篇文章介绍了如何将JSF与Sping Framework和Hibernate集成,并且给出了使用这些技术建立这个真实的Web应用程序的最佳实践和设计指导 JavaServer Faces(JSF)技术是J2EE应用程序的一个新的用户接口框架,它非常适合基于MVC(Model-View-Contro