Hibernate与Spring集成示例

简介:

    写了MyBatis与Spring的集成,今天写写Hibernate与Spring的集成。以前是别人集成好了自己直接用,今天自己集成一下。与MyBatis学习笔记系列一样,本篇依然采用courseman数据库(数据库的创建请参见笔者博客:MyBatis入门示例),及ant来管理工程(对ant不熟悉的朋友请参见笔者的相关博客:ant的下载与安装ant入门示例,)。本示例的任务是根据教师ID读取教师记录(教师类和表结构请参见笔者博客:MyBatis的association示例)。

一、版本说明

      Spring:3.1.2。

      Hibernate:3.6.7.Final。

      本示例提供源码下载(点此进入源码下载页面),因此需要的jar包就不一一赘述。

二、Spring的配置

      配置文件(beans.xml)的内容如下:

 
 
  1. <?xml version="1.0" encoding="utf8"?> 

  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.     xmlns:context="http://www.springframework.org/schema/context" 

  7.     xsi:schemaLocation="  

  8.             http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  

  9.             http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  

  10.             http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd  

  11.             http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd  

  12.             http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"  

  13.             default-autowire="byName" default-lazy-init="false"> 

  14.     

  15.   <!--本示例采用DBCP数据源,应预先把DBCP的jar包复制到工程的lib目录下。数据源配置如下--> 

  16.   <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> 

  17.      <property name="driverClassName" value="com.mysql.jdbc.Driver"/> 

  18.      <property name="url" 

  19.                value="jdbc:mysql://localhost/courseman"/> 

  20.      <property name="username" value="courseman"/> 

  21.      <property name="password" value="abc123"/> 

  22.   </bean> 

  23.  

  24.   <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> 

  25.      <!--dataSource属性指定要用到的数据源,因此在Hibernate的  

  26.      核心配置文件中就无需再配置与数据库连接相关的属性--> 

  27.      <property name="dataSource" ref="dataSource"/> 

  28.      <!--指定Hibernate核心配置文件--> 

  29.      <property name="configLocation" value="resources/hibernate.cfg.xml"/> 

  30.   </bean>   

  31.  

  32. </beans> 

      需要注意的是,以上sessionFactory的配置有其特殊之处。它的class是org.springframework.orm.hibernate3.LocalSessionFactoryBean,此类实现了Srping中的一个接口org.springframework.beans.factory.FactoryBean,这个接口声明了一个方法getObject()。这意味着,当我们要引用sessionFactory这个bean的时候,返回的不是类LocalSessionFactoryBean的实例,而是此实例的getObject()方法的返回值。而LocalSessionFactoryBean对此方法的实现(实际上是从AbstractSessionFactoryBean继承而来),是返回了一个SessionFactory对象。也就是说,LocalSessionFactoryBean的实例是用来生成SessionFactory对象的工厂。

      这与MyBatis和Spring的集成是一样的(请参见笔者博文:MyBatis与Spring集成示例),看来天下乌鸦一般黑啊!不过这倒是减轻了我们的学习、记忆负担。所不同的是,MyBatis的SqlSessionFactoryBean(类似于LocalSessionFactoryBean)是MyBatis自己实现的,而LocalSessionFactoryBean是Spring实现的。原因是Spring 3未提供与MyBatis 3的集成,MyBatis只好自己亲自上阵了(相关信息英文请参见:http://www.mybatis.org/spring/index.html,中文请参见:http://www.mybatis.org/spring/zh/index.html)。

三、Hibernate的配置

      Hibernate的核心配置文件hibernate.cfg.xml的内容如下: 

 
 
  1. <?xml version='1.0' encoding='utf8'?> 

  2. <!--  

  3.   ~ Hibernate, Relational Persistence for Idiomatic Java  

  4.   ~  

  5.   ~ Copyright (c) 2010, Red Hat Inc. or third-party contributors as  

  6.   ~ indicated by the @author tags or express copyright attribution  

  7.   ~ statements applied by the authors.  All third-party contributions are  

  8.   ~ distributed under license by Red Hat Inc.  

  9.   ~  

  10.   ~ This copyrighted material is made available to anyone wishing to use, modify,  

  11.   ~ copy, or redistribute it subject to the terms and conditions of the GNU  

  12.   ~ Lesser General Public License, as published by the Free Software Foundation.  

  13.   ~  

  14.   ~ This program is distributed in the hope that it will be useful,  

  15.   ~ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY  

  16.   ~ or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License  

  17.   ~ for more details.  

  18.   ~  

  19.   ~ You should have received a copy of the GNU Lesser General Public License  

  20.   ~ along with this distribution; if not, write to:  

  21.   ~ Free Software Foundation, Inc.  

  22.   ~ 51 Franklin Street, Fifth Floor  

  23.   ~ Boston, MA  02110-1301  USA  

  24.   --> 

  25. <!DOCTYPE hibernate-configuration PUBLIC  

  26.         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  

  27.         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 

  28.  

  29. <hibernate-configuration> 

  30.  

  31.     <session-factory> 

  32.  

  33.         <!-- 数据库方言 --> 

  34.         <property name="dialect">org.hibernate.dialect.MySQLDialect</property> 

  35.  

  36.         <!-- Enable Hibernate's automatic session context management --> 

  37.         <property name="current_session_context_class">thread</property> 

  38.  

  39.         <!-- Disable the second-level cache  --> 

  40.         <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> 

  41.           

  42.         <!-- 打印输出执行的SQL语句 --> 

  43.         <property name="show_sql">true</property> 

  44.  

  45.         <mapping resource="resources/mappers/Teacher.hbm.xml" /> 

  46.          

  47.     </session-factory> 

  48.  

  49. </hibernate-configuration> 

       Spring还提供了一种配置方式,可代替hibernate.cfg.xml。配置如下(配置文件是工程根目录下的beans2.xml): 

 
 
  1. <?xml version="1.0" encoding="utf8"?> 

  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.     xmlns:context="http://www.springframework.org/schema/context" 

  7.     xsi:schemaLocation="  

  8.             http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  

  9.             http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  

  10.             http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd  

  11.             http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd  

  12.             http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"  

  13.             default-autowire="byName" default-lazy-init="false"> 

  14.     

  15.   <!--本示例采用DBCP数据源,应预先把DBCP的jar包复制到工程的lib目录下。数据源配置如下--> 

  16.   <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> 

  17.      <property name="driverClassName" value="com.mysql.jdbc.Driver"/> 

  18.      <property name="url" 

  19.                value="jdbc:mysql://localhost/courseman"/> 

  20.      <property name="username" value="courseman"/> 

  21.      <property name="password" value="abc123"/> 

  22.   </bean> 

  23.  

  24.   <!--SessionFactory的另一种配置方式。这种方式可取代Hibernate的核心配置文件,因为如以下配置所示,  

  25.   Hibernate的各种属性、实体映射文件等,都可以用这种方式配置--> 

  26.   <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> 

  27.      <!--dataSource属性指定要用到的连接池--> 

  28.      <property name="dataSource" ref="dataSource"/> 

  29.      <!--指定要用到的实体映射文件--> 

  30.      <property name="mappingResources"> 

  31.           <list> 

  32.              <value>resources/mappers/Teacher.hbm.xml</value> 

  33.           </list> 

  34.      </property> 

  35.      <!--配置Hibernate的属性--> 

  36.      <property name="hibernateProperties"> 

  37.         <value> 

  38.            <!--数据库方言--> 

  39.            hibernate.dialect=org.hibernate.dialect.MySQLDialect  

  40.            <!-- 打印输出执行的SQL语句 --> 

  41.            hibernate.show_sql=true 

  42.         </value> 

  43.      </property> 

  44.   </bean> 

  45.  

  46. </beans>  

       教师实体映射文件内容如下: 

 
 
  1. <?xml version="1.0"?> 

  2. <!DOCTYPE hibernate-mapping PUBLIC  

  3.     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  

  4.     "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

  5.  

  6. <hibernate-mapping package="com.abc.domain"> 

  7.  

  8.     <class name="Teacher" table="TEACHER"> 

  9.         <id name="id" type="java.lang.Integer" column="ID"> 

  10.             <generator class="native"/> 

  11.         </id> 

  12.         <property name="name"/> 

  13.         <property name="gender"/> 

  14.         <property name="researchArea" column="RESEARCH_AREA"/> 

  15.         <property name="title"/>          

  16.     </class> 

  17.  

  18. </hibernate-mapping> 

 四、执行类

      执行类(HibernateSpringDemo.java)的代码如下。 

 
 
  1. package com.demo;  

  2.  

  3. import org.springframework.context.ApplicationContext;  

  4. import com.abc.domain.Teacher;  

  5. import org.springframework.context.support.ClassPathXmlApplicationContext;  

  6. import org.hibernate.SessionFactory;  

  7. import org.hibernate.Session;  

  8.  

  9.  

  10. public class HibernateSpringDemo  

  11. {  

  12.     private static ApplicationContext ctx;  

  13.       

  14.     static 

  15.     {  

  16.         //在类路径下寻找resources/beans.xml文件  

  17.         ctx = new ClassPathXmlApplicationContext("resources/beans.xml");  

  18.     }  

  19.       

  20.       

  21.     public static void main(String[] args)  

  22.     {  

  23.         //从Spring容器中请求SessionFactory  

  24.         SessionFactory factory =   

  25.                (SessionFactory)ctx.getBean("sessionFactory");  

  26.  

  27.         Session session = factory.openSession();  

  28.    

  29.         //读取id为1的教师。  

  30.         Teacher teacher = (Teacher)session.get(Teacher.class1);  

  31.  

  32.         if(teacher != null)  

  33.         {  

  34.             System.out.println("姓    名: " + teacher.getName());  

  35.             System.out.println("研究方向: " + teacher.getResearchArea());  

  36.         }  

  37.  

  38.         else 

  39.         {  

  40.             System.out.println("未找到!");  

  41.         }  

  42.           

  43.         session.close();  

  44.        

  45.     }  

  46.  

       修改ant的build.xml文件的run target,指定此类为执行类。

 
 
  1. <target name="run" depends="compile"> 

  2.       <!--指定HibernateSpringDemo为要运行的类--> 

  3.       <java fork="true" classname="com.demo.HibernateSpringDemo" 

  4.       classpathref="library"> 

  5.         <classpath path="${targetdir}"/> 

  6.       </java> 

  7. </target>   

 

执行结果如下:

五、可能会遇到的错误

      1、缺少javassist包

      对于需要的jar包,笔者并没有一次性把Spring和Hibernate提供的所有jar包全部用上,而是根据编译、运行时报出的找不到类的异常信息,找到相关的jar包,然后再复制到工程的lib目录下。然而,在编程过程中,却遇到了这个错误:java.lang.ExceptionInInitializerError,内嵌的异常是:org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]。上网查询,才得知是少了javassist包。感到奇怪的是,这次却没有报找不到类的异常信息。Hibernate发布包下有个lib目录,存放着Hibernate的jar包。它有个required(必需的)子目录,javassist包就在此目录下。既然是必需的,那就把此目录下的jar包全部用上吧,免得再出错后又得花上不少时间来排错。

      2、字符集问题

      hibernate.cfg.xml的编码本为utf-8,添加中文注释后报错:Could not parse configuration。把编码改为utf8或gbk后即可解决此问题。对于这个问题,Spring、MyBatis和ant,都是一个德行(请参见笔者博文&ldquo;MyBatis与Spring集成示例&rdquo;中的第五部分可能会遇到的错误中的&ldquo;2、字符集问题&rdquo;)。










本文转自 NashMaster2011 51CTO博客,原文链接:http://blog.51cto.com/legend2011/963649,如需转载请自行联系原作者
相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
目录
相关文章
|
11月前
|
数据可视化 Java BI
将 Spring 微服务与 BI 工具集成:最佳实践
本文探讨了 Spring 微服务与商业智能(BI)工具集成的潜力与实践。随着微服务架构和数据分析需求的增长,Spring Boot 和 Spring Cloud 提供了构建可扩展、弹性服务的框架,而 BI 工具则增强了数据可视化与实时分析能力。文章介绍了 Spring 微服务的核心概念、BI 工具在企业中的作用,并深入分析了两者集成带来的优势,如实时数据处理、个性化报告、数据聚合与安全保障。同时,文中还总结了集成过程中的最佳实践,包括事件驱动架构、集中配置管理、数据安全控制、模块化设计与持续优化策略,旨在帮助企业构建高效、智能的数据驱动系统。
483 1
将 Spring 微服务与 BI 工具集成:最佳实践
|
XML 人工智能 Java
Spring Boot集成Aviator实现参数校验
Aviator是一个高性能、轻量级的Java表达式求值引擎,适用于动态表达式计算。其特点包括支持多种运算符、函数调用、正则匹配、自动类型转换及嵌套变量访问,性能优异且依赖小。适用于规则引擎、公式计算和动态脚本控制等场景。本文介绍了如何结合Aviator与AOP实现参数校验,并附有代码示例和仓库链接。
741 0
|
安全 Java 数据库
第16课:Spring Boot中集成 Shiro
第16课:Spring Boot中集成 Shiro
1201 0
|
消息中间件 存储 Java
第15课: Spring Boot中集成ActiveMQ
第15课: Spring Boot中集成ActiveMQ
730 0
|
人工智能 Java 测试技术
Spring Boot 集成 JUnit 单元测试
本文介绍了在Spring Boot中使用JUnit 5进行单元测试的常用方法与技巧,包括添加依赖、编写测试类、使用@SpringBootTest参数、自动装配测试模块(如JSON、MVC、WebFlux、JDBC等),以及@MockBean和@SpyBean的应用。内容实用,适合Java开发者参考学习。
1381 0
|
11月前
|
监控 Cloud Native Java
Spring Integration 企业集成模式技术详解与实践指南
本文档全面介绍 Spring Integration 框架的核心概念、架构设计和实际应用。作为 Spring 生态系统中的企业集成解决方案,Spring Integration 基于著名的 Enterprise Integration Patterns(EIP)提供了轻量级的消息驱动架构。本文将深入探讨其消息通道、端点、过滤器、转换器等核心组件,以及如何构建可靠的企业集成解决方案。
912 0
|
Java 关系型数据库 数据库连接
Spring Boot项目集成MyBatis Plus操作PostgreSQL全解析
集成 Spring Boot、PostgreSQL 和 MyBatis Plus 的步骤与 MyBatis 类似,只不过在 MyBatis Plus 中提供了更多的便利功能,如自动生成 SQL、分页查询、Wrapper 查询等。
1092 2
|
缓存 JSON 前端开发
第07课:Spring Boot集成Thymeleaf模板引擎
第07课:Spring Boot集成Thymeleaf模板引擎
1030 0
第07课:Spring Boot集成Thymeleaf模板引擎
|
Java 数据库连接 API
Java 8 + 特性及 Spring Boot 与 Hibernate 等最新技术的实操内容详解
本内容涵盖Java 8+核心语法、Spring Boot与Hibernate实操,按考试考点分类整理,含技术详解与代码示例,助力掌握最新Java技术与应用。
371 2