`
icarusliu
  • 浏览: 235444 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

在spring当中启用hibernate

阅读更多

有两种方式:

1. 在springContext.xml当中配置sessionFactory,然后就可以将这个SessionFactory注入到其它要使用hibernate的DAO当中去。

	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="configLocation">
			<value>classpath:hibernate.cfg.xml</value>
		</property>
	</bean>
	
	<bean id="test" class="TestDAO">
		<property name="sessionFactory">
			<ref local="sessionFactory"/>
		</property>
	</bean>

  这样,在TestDAO这个类当中就可以直接用SessionFactory来操作数据库了。

 

2. 不在xml文件当中进行配置,生成单独的一个类来通过hibernate.cfg.xml文件的位置来取得sessionFactory。这种方式其实就是上一种方式自己来实现。

下面是MyEclipse自动生成的一个sessionFactory的管理类,用户也可以自行实现。

package com.unews.hibernate.data;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

/**
 * Configures and provides access to Hibernate sessions, tied to the
 * current thread of execution.  Follows the Thread Local Session
 * pattern, see {@link http://hibernate.org/42.html }.
 */
public class HibernateSessionFactory {

    /** 
     * Location of hibernate.cfg.xml file.
     * Location should be on the classpath as Hibernate uses  
     * #resourceAsStream style lookup for its configuration file. 
     * The default classpath location of the hibernate config file is 
     * in the default package. Use #setConfigFile() to update 
     * the location of the configuration file for the current session.   
     */
    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private  static Configuration configuration = new Configuration();
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;

	static {
    	try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err
					.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
    }
    private HibernateSessionFactory() {
    }
	
	/**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();

		if (session == null || !session.isOpen()) {
			if (sessionFactory == null) {
				rebuildSessionFactory();
			}
			session = (sessionFactory != null) ? sessionFactory.openSession()
					: null;
			threadLocal.set(session);
		}

        return session;
    }

	/**
     *  Rebuild hibernate session factory
     *
     */
	public static void rebuildSessionFactory() {
		try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err
					.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}

	/**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

	/**
     *  return session factory
     *
     */
	public static org.hibernate.SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
     *  return session factory
     *
     *	session factory will be rebuilded in the next call
     */
	public static void setConfigFile(String configFile) {
		HibernateSessionFactory.configFile = configFile;
		sessionFactory = null;
	}

	/**
     *  return hibernate configuration
     *
     */
	public static Configuration getConfiguration() {
		return configuration;
	}

}

 

分享到:
评论

相关推荐

    spring mvc + spring + hibernate 全注解整合开发视频教程 11

    在这个视频教程中,你可能将学习到如何配置Spring的XML上下文文件以启用注解驱动的配置,如何在Spring MVC中创建注解式的控制器并处理HTTP请求,以及如何通过Hibernate的注解来设计数据模型并执行CRUD操作。...

    Spring集成的Hibernate配置二级缓存

    以EhCache为例,我们需要在项目中引入ehcache-core或ehcache的依赖,并在Hibernate配置文件(hibernate.cfg.xml或persistence.xml)中启用二级缓存,添加如下配置: ```xml &lt;property name="hibernate.cache.use_...

    Struts2+Spring4+Hibernate5整合

    配置全局结果类型和常量,如`struts.objectFactory`设为`spring`,以启用Spring管理Action。 3. **配置Spring**:创建Spring的配置文件(如applicationContext.xml),声明Bean,包括Action类、DAO接口及其实现、...

    spring struts2 hibernate dwr

    Spring、Struts2、Hibernate和Direct Web Remoting (DWR) 是四种非常流行的Java开源框架,它们分别在不同层面提供了强大的功能。下面我们将深入探讨这些框架的基本概念及其整合过程。 **Spring框架** Spring 是一个...

    spring与hibernate的整合

    在 Spring 中使用 Hibernate 通常有两种方式:一是使用 HibernateTemplate 或 HibernateDaoSupport,另一种是直接使用 Hibernate 的原生 API。这里我们关注后者,通过 Spring 注入 SessionFactory 到 DAO 类中,然后...

    在Spring中配置Hibernate事务

    在Spring框架中集成和配置Hibernate事务管理是企业级Java应用中的常见实践,它能提供高效且灵活的事务处理策略。Spring作为一款强大的依赖注入(DI)和面向切面编程(AOP)容器,能够轻松地管理和协调不同数据访问...

    struts-2.3、spring2.5.6、hibernate3.3整合示例

    6. **事务管理**:Spring提供声明式事务管理,通过`@Transactional`注解在方法级别或类级别上启用事务。 7. **测试和优化**:完成整合后,进行功能测试和性能优化,确保所有组件协同工作,提高应用程序的响应速度和...

    spring3 hibernate4 ehcache实例

    Spring3支持Hibernate的二级缓存,可以通过注解来启用或禁用缓存。例如,使用`@Cacheable`、`@CacheEvict`和`@CacheConfig`等注解,分别用于读取缓存、清除缓存和全局缓存配置。 4. **实体类缓存配置** 对于需要...

    spring3,hibernate4 配置声明式事务管理(annotation方式)

    在Java开发中,Spring框架和Hibernate ORM工具是两个非常重要的组件。Spring提供了强大的依赖注入(DI)和面向切面编程(AOP),而Hibernate则是一个优秀的对象关系映射(ORM)解决方案,使得开发者可以方便地操作...

    hibernate与spring整合demo

    6. 配置事务管理:在Spring配置文件中启用事务管理,并定义事务边界。 7. 测试整合:编写测试用例,验证Spring如何管理和调用Hibernate完成数据操作。 五、示例代码 例如,创建一个User实体类,对应的DAO接口和实现...

    Spring4+Hibernate4二级缓存实例源码

    2. **配置Hibernate**:在hibernate.cfg.xml配置文件中,启用二级缓存并指定缓存提供者。例如: ```xml &lt;property name="hibernate.cache.use_second_level_cache"&gt;true &lt;property name="hibernate.cache.region....

    struts+spring+hibernate三大框架整合

    2. **事务管理**:Spring提供声明式事务管理,通过`&lt;tx:annotation-driven&gt;`启用基于注解的事务管理,或在配置文件中手动配置事务规则。 3. **DAO层的实现**:Spring的`HibernateTemplate`或`HibernateOperations`...

    struts2+spring3+hibernate4整合所用jar包

    在"struts-2.3.1.2+spring-3.2.4+hibernate-4.1.0_所用jar包"这个压缩包中,包含的应该是整合SSH所需的所有依赖库。这些jar包涵盖了Struts2、Spring3和Hibernate4的核心功能,以及可能需要的其他库,如数据库驱动、...

    spring、 spring mvc、 hibernate、 ehcache JavaWeb后台框架

    在Spring框架中,Ehcache可以与Spring Cache模块集成,方便地在项目中启用缓存功能。 这四个框架的整合使用,能够构建出一套完整的JavaWeb后台解决方案。Spring作为基础框架,提供整体的管理和服务;Spring MVC处理...

    spring+hibernate+flex整合

    5. **配置BlazeDS**:在Spring配置文件中添加BlazeDS的配置,启用Remoting服务。 6. **创建Flex项目**:在Flex IDE中新建项目,导入BlazeDS库,配置RemoteObject来连接Spring服务。 7. **编写Flex UI**:设计和实现...

    spring+hibernate

    在IT行业中,Spring和Hibernate是两个非常重要的框架,它们在企业级Java应用开发中起着核心作用。Spring是一个全面的后端开发框架,提供依赖注入、AOP(面向切面编程)、MVC(模型-视图-控制器)以及其他许多功能。...

    spring3、 hibernate4 配置声明式事务管理(annotation方式)

    在Spring的配置文件中,我们需要添加`&lt;tx:annotation-driven&gt;`元素来启用基于注解的事务管理,并指定事务管理器。例如: ```xml &lt;bean id="transactionManager" class="org.springframework.orm.hibernate4....

    Struts2.3.28+spring4.1.6+hibernate4.3.8整合总结(注解)

    Struts2.3.28、Spring4.1.6和Hibernate...以上就是Struts2.3.28、Spring4.1.6和Hibernate4.3.8整合的关键知识点,以及注解在整合中的作用。理解并熟练掌握这些内容,能够帮助开发者更有效地构建和维护Java EE应用程序。

    spring3+hibernate4+springmvc+druid连接池

    【标题】"spring3+hibernate4+springmvc+druid连接池"是一个常见的Java Web开发中的技术栈整合,其中包含了Spring框架的三个主要组件:Spring Core、Spring MVC和Hibernate ORM,以及Druid数据库连接池。这个组合常...

    JSF+Spring+Hibernate的实例讲解.doc

    3. **整合 Hibernate**:Spring 支持 Hibernate 的集成,可以在 Spring 配置文件中定义 SessionFactory,并通过 Spring 的事务管理器处理事务。这样,Managed Beans 可以直接使用 Spring 提供的 DAO 对象,无需关心...

Global site tag (gtag.js) - Google Analytics