Hibernate与Spring集成示例

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,高可用系列 2核4GB
云数据库 RDS PostgreSQL,高可用系列 2核4GB
简介:

    写了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,如需转载请自行联系原作者
相关实践学习
如何快速连接云数据库RDS MySQL
本场景介绍如何通过阿里云数据管理服务DMS快速连接云数据库RDS MySQL,然后进行数据表的CRUD操作。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
4月前
|
安全 Java Apache
微服务——SpringBoot使用归纳——Spring Boot中集成 Shiro——Shiro 身份和权限认证
本文介绍了 Apache Shiro 的身份认证与权限认证机制。在身份认证部分,分析了 Shiro 的认证流程,包括应用程序调用 `Subject.login(token)` 方法、SecurityManager 接管认证以及通过 Realm 进行具体的安全验证。权限认证部分阐述了权限(permission)、角色(role)和用户(user)三者的关系,其中用户可拥有多个角色,角色则对应不同的权限组合,例如普通用户仅能查看或添加信息,而管理员可执行所有操作。
153 0
|
4月前
|
安全 Java 数据安全/隐私保护
微服务——SpringBoot使用归纳——Spring Boot中集成 Shiro——Shiro 三大核心组件
本课程介绍如何在Spring Boot中集成Shiro框架,主要讲解Shiro的认证与授权功能。Shiro是一个简单易用的Java安全框架,用于认证、授权、加密和会话管理等。其核心组件包括Subject(认证主体)、SecurityManager(安全管理员)和Realm(域)。Subject负责身份认证,包含Principals(身份)和Credentials(凭证);SecurityManager是架构核心,协调内部组件运作;Realm则是连接Shiro与应用数据的桥梁,用于访问用户账户及权限信息。通过学习,您将掌握Shiro的基本原理及其在项目中的应用。
153 0
|
4月前
|
NoSQL Java 关系型数据库
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Redis 介绍
本文介绍在 Spring Boot 中集成 Redis 的方法。Redis 是一种支持多种数据结构的非关系型数据库(NoSQL),具备高并发、高性能和灵活扩展的特点,适用于缓存、实时数据分析等场景。其数据以键值对形式存储,支持字符串、哈希、列表、集合等类型。通过将 Redis 与 Mysql 集群结合使用,可实现数据同步,提升系统稳定性。例如,在网站架构中优先从 Redis 获取数据,故障时回退至 Mysql,确保服务不中断。
150 0
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Redis 介绍
|
3月前
|
Java 开发工具 Spring
【Azure Application Insights】为Spring Boot应用集成Application Insight SDK
本文以Java Spring Boot项目为例,详细说明如何集成Azure Application Insights SDK以收集和展示日志。内容包括三步配置:1) 在`pom.xml`中添加依赖项`applicationinsights-runtime-attach`和`applicationinsights-core`;2) 在main函数中调用`ApplicationInsights.attach()`;3) 配置`applicationinsights.json`文件。同时提供问题排查建议及自定义日志方法示例,帮助用户顺利集成并使用Application Insights服务。
|
4月前
|
消息中间件 存储 Java
微服务——SpringBoot使用归纳——Spring Boot中集成ActiveMQ——ActiveMQ安装
本教程介绍ActiveMQ的安装与基本使用。首先从官网下载apache-activemq-5.15.3版本,解压后即可完成安装,非常便捷。启动时进入解压目录下的bin文件夹,根据系统选择win32或win64,运行activemq.bat启动服务。通过浏览器访问`http://127.0.0.1:8161/admin/`可进入管理界面,默认用户名密码为admin/admin。ActiveMQ支持两种消息模式:点对点(Queue)和发布/订阅(Topic)。前者确保每条消息仅被一个消费者消费,后者允许多个消费者同时接收相同消息。
109 0
微服务——SpringBoot使用归纳——Spring Boot中集成ActiveMQ——ActiveMQ安装
|
4月前
|
消息中间件 Java 微服务
微服务——SpringBoot使用归纳——Spring Boot中集成ActiveMQ——发布/订阅消息的生产和消费
本文详细讲解了Spring Boot中ActiveMQ的发布/订阅消息机制,包括消息生产和消费的具体实现方式。生产端通过`sendMessage`方法发送订阅消息,消费端则需配置`application.yml`或自定义工厂以支持topic消息监听。为解决点对点与发布/订阅消息兼容问题,可通过设置`containerFactory`实现两者共存。最后,文章还提供了测试方法及总结,帮助读者掌握ActiveMQ在异步消息处理中的应用。
139 0
|
4月前
|
消息中间件 网络协议 Java
微服务——SpringBoot使用归纳——Spring Boot中集成ActiveMQ——ActiveMQ集成
本文介绍了在 Spring Boot 中集成 ActiveMQ 的详细步骤。首先通过引入 `spring-boot-starter-activemq` 依赖并配置 `application.yml` 文件实现基本设置。接着,创建 Queue 和 Topic 消息类型,分别使用 `ActiveMQQueue` 和 `ActiveMQTopic` 类完成配置。随后,利用 `JmsMessagingTemplate` 实现消息发送功能,并通过 Controller 和监听器实现点对点消息的生产和消费。最后,通过浏览器访问测试接口验证消息传递的成功性。
126 0
|
4月前
|
消息中间件 Java API
微服务——SpringBoot使用归纳——Spring Boot中集成ActiveMQ—— JMS 和 ActiveMQ 介绍
本文介绍如何在Spring Boot中集成ActiveMQ,首先阐述了JMS(Java消息服务)的概念及其作为与具体平台无关的API在异步通信中的作用。接着说明了JMS的主要对象模型,如连接工厂、会话、生产者和消费者等,并指出JMS支持点对点和发布/订阅两种消息类型。随后重点讲解了ActiveMQ,作为Apache开源的消息总线,它完全支持JMS规范,适用于异步消息处理。最后,文章探讨了在Spring Boot中使用队列(Queue)和主题(Topic)这两种消息通信形式的方法。
95 0
|
4月前
|
NoSQL Java API
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Spring Boot 集成 Redis
本文介绍了在Spring Boot中集成Redis的方法,包括依赖导入、Redis配置及常用API的使用。通过导入`spring-boot-starter-data-redis`依赖和配置`application.yml`文件,可轻松实现Redis集成。文中详细讲解了StringRedisTemplate的使用,适用于字符串操作,并结合FastJSON将实体类转换为JSON存储。还展示了Redis的string、hash和list类型的操作示例。最后总结了Redis在缓存和高并发场景中的应用价值,并提供课程源代码下载链接。
322 0
|
4月前
|
NoSQL Java Redis
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Redis 安装
本教程介绍在 VMware 虚拟机(CentOS 7)或阿里云服务器中安装 Redis 的过程,包括安装 gcc 编译环境、下载 Redis(官网或 wget)、解压安装、修改配置文件(如 bind、daemonize、requirepass 等设置)、启动 Redis 服务及测试客户端连接。通过 set 和 get 命令验证安装是否成功。适用于初学者快速上手 Redis 部署。
72 0

热门文章

最新文章