Spring+Hibernate_20_32

合集下载

SpringMVC+Spring+Hibernate框架整合原理,作用及使用方法

SpringMVC+Spring+Hibernate框架整合原理,作用及使用方法

SpringMVC+Spring+Hibernate框架整合原理,作⽤及使⽤⽅法SSM框架是spring MVC ,spring和mybatis框架的整合,是标准的MVC模式,将整个系统划分为表现层,controller层,service层,DAO层四层使⽤spring MVC负责请求的转发和视图管理spring实现业务对象管理,mybatis作为数据对象的持久化引擎原理:SpringMVC:1.客户端发送请求到DispacherServlet(分发器)2.由DispacherServlet控制器查询HanderMapping,找到处理请求的Controller3.Controller调⽤业务逻辑处理后,返回ModelAndView4.DispacherSerclet查询视图解析器,找到ModelAndView指定的视图5.视图负责将结果显⽰到客户端Spring:我们平时开发接触最多的估计就是IOC容器,它可以装载bean(也就是我们中的类,当然也包括service dao⾥⾯的),有了这个机制,我们就不⽤在每次使⽤这个类的时候为它初始化,很少看到关键字new。

另外spring的aop,事务管理等等都是我们经常⽤到的。

Mybatis:mybatis是对jdbc的封装,它让数据库底层操作变的透明。

mybatis的操作都是围绕⼀个sqlSessionFactory实例展开的。

mybatis通过配置⽂件关联到各实体类的Mapper⽂件,Mapper⽂件中配置了每个类对数据库所需进⾏的sql语句映射。

在每次与数据库交互时,通过sqlSessionFactory拿到⼀个sqlSession,再执⾏sql命令。

使⽤⽅法:要完成⼀个功能:1. 先写实体类entity,定义对象的属性,(可以参照数据库中表的字段来设置,数据库的设计应该在所有编码开始之前)。

2. 写Mapper.xml(Mybatis),其中定义你的功能,对应要对数据库进⾏的那些操作,⽐如 insert、selectAll、selectByKey、delete、update等。

hibernate的基本用法

hibernate的基本用法

hibernate的基本用法Hibernate是一个开源的Java框架,用于简化数据库操作。

它为开发人员提供了一个更加简单、直观的方式来管理数据库,同时也提高了应用程序的性能和可维护性。

本文将逐步介绍Hibernate的基本用法,包括配置、实体映射、数据操作等。

一、配置Hibernate1. 下载和安装Hibernate:首先,我们需要下载Hibernate的压缩包并解压。

然后将解压后的文件夹添加到Java项目的构建路径中。

2. 创建Hibernate配置文件:在解压后的文件夹中,可以找到一个名为"hibernate.cfg.xml"的文件。

这是Hibernate的主要配置文件,我们需要在其中指定数据库连接信息和其他相关配置。

3. 配置数据库连接:在"hibernate.cfg.xml"文件中,我们可以添加一个名为"hibernate.connection.url"的属性,用于指定数据库的连接URL。

除此之外,还需要指定数据库的用户名和密码等信息。

4. 配置实体映射:Hibernate使用对象关系映射(ORM)来将Java类映射到数据库表。

我们需要在配置文件中使用"mapping"元素来指定实体类的映射文件。

这个映射文件描述了实体类与数据库表之间的对应关系。

二、实体映射1. 创建实体类:我们需要创建一个Java类,用于表示数据库中的一行数据。

这个类的字段通常与数据库表的列对应。

同时,我们可以使用Hibernate提供的注解或XML文件来配置实体的映射关系。

2. 创建映射文件:可以根据个人喜好选择使用注解还是XML文件来配置实体类的映射关系。

如果使用XML文件,需要创建一个与实体类同名的XML文件,并在其中定义实体类与数据库表之间的映射关系。

3. 配置实体映射:在配置文件中,我们需要使用"mapping"元素来指定实体类的映射文件。

【计算机应用】_j2ee_期刊发文热词逐年推荐_20140723

【计算机应用】_j2ee_期刊发文热词逐年推荐_20140723

53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
科研热词 j2ee spring struts hibernate 框架 web服务 ejb soap j2ee1.4 acegi 高校教学评估 马可夫 面向服务的体系结构 面向服务架构 集群 过滤器 轻量级框架 轻量级 软件体系结构 车辆监控 资源共享 负载收集 负载指标 负载均衡 设计 认证管理器 认证 自恢复进化 自动化测试系统 聚合 网站内容管理 网格构件 统一数据模型 统一建模语言 系统架构 相关性分析法 电子运行维护系统 电子政务 灰色关联法 消息驱动bean(mdb) 模型机 模型-视图-控制器 构架 构件代理 构件cache 权限管理 智能元搜索引擎 智能交通系统 映射 日历队列 数据持久化层 数据字典
2008年 序号 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
政府内部服务库 政府公共总线 放缩算法 授权 持久化 扩展性 快件检验检疫 异构平台 应用服务器 实验数据管理 实体bean 多源数据 多层软件体系结构 多层次模糊综合绩效评价 多媒体数据存储 可扩展标记语言 动态自适应 共享系统 信息系统 信息模型 供应链管理系统 供应商绩效评估 会话bean 企业bean(ejb2.1) 企业bean(ejb) 产品生命周期管理 交易中间件 互操作性 中药药性 业务支撑系统 wsdl ws-i概要 wicket web数据库分页 web报表 webgis web.xml web services web tld tag struts框架 ssi soa session bean servlet/jsp servlet oracle intermedia o/r myeclipse mvc设计模式 mvc md5 jsp技术

达梦Hibernate Spring集成开发示例

达梦Hibernate Spring集成开发示例

达梦Hibernate Spring集成开发示例DM是武汉华工达梦数据库有限公司推出的新一代高性能、高安全性的数据库产品。

它具有开放的、可扩展的体系结构,高性能事务处理能力,以及低廉的维护成本。

DM是完全自主开发的数据库软件,其安全级别达到了国内所有数据库产品中的最高级---B1级。

在这里我准备用时下比较流行的开发工具,Hibernate和Spring,达梦数据库。

以及MyEclipse来完成一个简单的应用。

数据库采用达梦5.01、用达梦创建一个test数据库,再创建一个user表,再创建两个字段username和password。

脚本如下create database test datafile 'test.dbf' size 100;set current database testcreate login test identified by test123 default database test;create user test related by test;grant resource to test at test;以上脚本为创建test数据库,并且创建一个登陆名为test 密码是test123drop table xt_user;create table xt_user(user_id varchar(30) not null,user_name varchar(20) not null,user_pwd varchar(30) not null,primary key(user_id));2、打开myeclipse的database explore透视图,右键单击左侧的空白区域,点击new 按钮单击“configure database driver”来配置数据库的驱动。

完成以后,做如下操作:然后测试数据库是否连接成功。

如果测试成功显示如下图:1.新建一个web项目testSpring 2.引入Spring包注意:这里为了省得以后再添加spring的相关包,所以一次性的选中了所有的包。

Spring的HibernateTemplate

Spring的HibernateTemplate

使用spring的hibernateTemplate的方法分类:Struts+Hibernate+Spring2009-05-22 15:486178人阅读评论(6)收藏举报使用spring的hibernateTemplate的方法- [spring]版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明/logs/24775065.html1.管理SessionFactory使用Spring整合Hibernate时我们不需要hibernate.cfg.xml文件。

首先,在applicationContext.xml中配置数据源(dataSource)bean和session工厂(sessionFactory)bean。

其中,在配置session工厂bean 时,应该注入三个方面的信息:●数据源bean●所有持久化类的配置文件●Hibernate的SessionFactory的属性Hibernate的SessionFactory的属性信息又包括两个内容,一,Hibernate的连接方法;二,不同数据库连接,启动时的选择。

2.为HibernateTemplate注入SessionFactory对象,通过HibernateT emplate来持久化对象Spring提供了HibernateTemplate,用于持久层访问,该模板无需打开Session及关闭Session。

它只要获得SessionFactory的引用,将可以只能地打开Session,并在持久化访问结束后关闭Session,程序开发只需完成持久层逻辑,通用的操作(如对数据库中数据的增,删,改,查)则有HibernateTemplate完成。

HibernateTemplate有三个构造函数,不论是用哪一种构造,要使HibernateTemplate能完成持久化操作,都必须向其传入一个SessionFactory的引用。

HibernateTemplate的用法有两种,一种是常规的用法,另一种是复杂的用。

hibernate框架的工作原理

hibernate框架的工作原理

hibernate框架的工作原理Hibernate框架的工作原理Hibernate是一个开源的ORM(Object-Relational Mapping)框架,它将Java对象映射到关系型数据库中。

它提供了一种简单的方式来处理数据持久化,同时也提供了一些高级特性来优化性能和可维护性。

1. Hibernate框架的基本概念在开始讲解Hibernate框架的工作原理之前,需要先了解一些基本概念:Session:Session是Hibernate与数据库交互的核心接口,它代表了一个会话,可以用来执行各种数据库操作。

SessionFactory:SessionFactory是一个线程安全的对象,它用于创建Session对象。

通常情况下,应用程序只需要创建一个SessionFactory对象。

Transaction:Transaction是对数据库操作进行事务管理的接口。

在Hibernate中,所有对数据库的操作都应该在事务中进行。

Mapping文件:Mapping文件用于描述Java类与数据库表之间的映射关系。

它定义了Java类属性与数据库表字段之间的对应关系。

2. Hibernate框架的工作流程Hibernate框架主要分为两个部分:持久化层和业务逻辑层。

其中,持久化层负责将Java对象映射到数据库中,并提供数据访问接口;业务逻辑层则负责处理业务逻辑,并调用持久化层进行数据访问。

Hibernate框架的工作流程如下:2.1 创建SessionFactory对象在应用程序启动时,需要创建一个SessionFactory对象。

SessionFactory是一个线程安全的对象,通常情况下只需要创建一个即可。

2.2 创建Session对象在业务逻辑层需要进行数据访问时,需要先创建一个Session对象。

Session是Hibernate与数据库交互的核心接口,它代表了一个会话,可以用来执行各种数据库操作。

2.3 执行数据库操作在获取了Session对象之后,就可以执行各种数据库操作了。

【SpringFramework】Spring入门教程(三)使用注解配置

【SpringFramework】Spring入门教程(三)使用注解配置

【SpringFramework】Spring⼊门教程(三)使⽤注解配置本⽂主要介绍四个⽅⾯:(1) 注解版本IOC和DI(2) Spring纯注解(3) Spring测试(4) SpringJDBC - Spring对数据库的操作使⽤注解配置Spring⼊门说在前⾯学习基于注解的IoC配置,⼤家脑海⾥⾸先得有⼀个认知,即注解配置和xml配置要实现的功能都是⼀样的,都是要降低模块间的耦合度。

仅仅只是配置的形式不⼀样。

关于实际的开发中到底使⽤xml还是注解,每家公司有着不同的使⽤习惯。

所以这两种配置⽅式我们都需要掌握。

基于注解配置的⽅式也已经逐渐代替xml配置。

所以我们必须要掌握使⽤注解的⽅式配置Spring。

配置步骤注意:如果使⽤Eclipse需要先安装了STS插件,或者使⽤STS开发⼯具创建项⽬。

本⽂使⽤IDEA进⾏演⽰。

1.2.1. 第⼀步:拷贝必备jar包到⼯程的lib⽬录。

注意:在基于注解的配置中,我们还要多拷贝⼀个aop的jar包。

如下图:1.2.2. 第⼆步:在类的根路径下创建⼀个任意名称的xml⽂件(不能是中⽂)注意:基于注解整合时,Spring配置⽂件导⼊约束时需要多导⼊⼀个context命名空间下的约束。

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xmlns:context="/schema/context"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans.xsd/schema/context/schema/context/spring-context.xsd"></beans>1.2.3. 第⼆步:创建⼀个服务类创建⼀个测试的服务类,并且加⼊使⽤@Component注解,声明该类允许注⼊到Spring容器package org.cjw.service;import ponent;/*使⽤注解配置时,需要将Spring框架启动就创建对象的类表⽰为组件类表⽰组件类使⽤@Component注解*/@Componentpublic class CustomerService {public void save() {System.out.println("-保存数据-");}}1.2.4. 第四步在spring的配置⽂件加⼊扫描注解<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xmlns:context="/schema/context"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans.xsd/schema/context/schema/context/spring-context.xsd"><!-- 声明扫描包及其⼦包的类,如果发现有组件注解的类,就创建对象并加⼊到容器中去 --><context:component-scan base-package="org.cjw" /></beans>1.2.5. 第五步:测试调⽤代码package org.cjw.test;import org.cjw.service.CustomerService;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class CustomerServiceTest {@Testpublic void testSave() {ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");CustomerService customerService = context.getBean(CustomerService.class);customerService.save();}}--测试结果,如果可以调⽤服务⽅法,测试成功。

Hibernate基础知识详解

Hibernate基础知识详解

Hibernate基础知识详解<hibernate-mapping><class name="*.*.*" table="t_customer" catalog="***"><id name="id" column="c_id"><generator class="identity"/></id><property name="name" column="c_name" length="20"/><set name="orders" inverse="false" cascade="save-update"><key column="c_customer_id"/></set></class></hibernate-mapping>(1)统⼀声明包名,这样在<class>中就不需要写类的全名。

(2)关于<class>标签配置name 属性:类的全名称table 表的名称,可以省略,这时表的名称就与类名⼀致catalog 属性:数据库名称可以省略.如果省略,参考核⼼配置⽂件中 url 路径中的库名称(3)关于<id>标签,<id>是⽤于建⽴类中的属性与表中的主键映射。

name 类中的属性名称column 表中的主键名称 column 它也可以省略,这时列名就与类中属性名称⼀致length 字段长度type 属性指定类型<generator>它主要是描述主键⽣成策略。

【计算机应用】_spring_期刊发文热词逐年推荐_20140723

【计算机应用】_spring_期刊发文热词逐年推荐_20140723

2012年 序号 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
科研热词 spring 轨道平直度 知识管理 流动 泛型编程 泛型dao 泛型 替补 春运 时间序列流 数据库访问 数据分页显示 提前终止 探讨 技术资料管理 工厂模式 大容量数据的读写 售票车 受限 动车检修 动态轮重检测设备 动态弯曲 信息技术 专家库 xml taskscheduler taskexecutor struts框架 struts2 sql server spring框架 spring任务调度 spring3.x rest风格web服务 resttemplate rest quartz mvc json消息 jsf jpa框架 jdk jdbc模板 jdbctemplate jbpm hibernate ajax @scheduled注解
推荐指数 4 3 3 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
2010年 序号 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42

SSH_三大框架介绍

SSH_三大框架介绍

SSH_三大框架介绍SSH是指Struts、Spring和Hibernate三个开源框架的整合,其中每个框架都有自己的设计思想和特点,通过整合,可以充分发挥它们的优势,提高开发效率和系统性能。

下面将分别介绍这三个框架。

1. Struts:Struts是一个基于MVC设计模式的Web应用程序框架,它将应用程序分为三个层:模型(Model)、视图(View)和控制器(Controller)。

模型负责处理业务逻辑,视图负责展示数据,控制器负责接收用户输入和导航请求。

Struts通过配置文件定义请求的映射和处理逻辑,通过统一的控制器Servlet接收请求,根据配置文件将请求转发给相应的Action。

在Action中进行请求处理和业务逻辑的实现。

2. Spring:Spring是一个轻量级的IoC(Inverse of Control)容器和应用程序框架,它主要解决企业应用中的复杂性问题。

Spring的核心思想是面向接口编程和依赖注入。

通过Spring的IoC容器管理对象的生命周期和依赖关系,将对象的创建和销毁过程交给容器处理。

通过依赖注入,可以将对象之间的依赖关系解耦,提高代码的可维护性和可测试性。

Spring还提供了丰富的功能模块,如AOP(Aspect-Oriented Programming)框架、事务管理、远程调用等,可以在应用程序中灵活地配置和使用。

Spring的优点是具有良好的灵活性和扩展性,可以与其他框架进行无缝集成,支持多种数据库和应用服务器。

同时,Spring还提供了很强的层次化管理和面向切面编程的能力,使得开发人员可以更加精细地控制应用程序的流程和行为。

3. Hibernate:Hibernate是一个开源的对象关系映射框架,用于将Java对象映射到关系数据库中的表结构上。

Hibernate通过配置文件和注解,提供了一种方便的方式来实现数据的持久化和检索。

Hibernate根据对象的映射关系,自动生成相应的SQL语句,实现了对象与数据库之间的映射和转换。

Spring+Hibernate查询中中文乱码的解决方案

Spring+Hibernate查询中中文乱码的解决方案

出错 , 作者继承了 Oal Da et r e ii ma 2中注册就没错 。在 h e t . 中需解决的问题 : b e ir e0 ba 3 n 第一 , 在使用 l e 模糊查询时 , Q 语句的执行出现的中文乱码 i 做 k H L
得 到相关系数 p 09 1 , - . 大于阈值 08 所 以可以判 为同一人。图 4 b 为 27 ., ()
图 3 图 像 预 处理 过 程
不同人 的实验数据 , 其相关系数 p 0 8 , = . 8 小于 阈值 0 , 2 2 . 可以判为不同 8 人, 实验成功。 从小范 围实验结果可 以看到 , 系统基本能达到较 高的技术
[ ] L h — ug F nK o C i Bo e cvr ct n u n eml 3 i C L n' a u - h . i t e f a o s g t r a n i n m f i i i i i h
i ae f am- os enp trs [ IE rnatoso i ut a d m gso l d r vi at n J . ETasc n nCr i p a e JE i c sn
问题 。
Hbr t用 的却是 U F 8 因此 , ie a ne T- 。 每当进行 数据查询的时候, 显示 的都是
乱码。
第二 , 使用 l e l 查询并做分页时 , k 最后一 页会报错 , 错误如下 :
2 实 验 数 据 分 析 . 2
图 4 a 为同一人 的实验 数据 , () 经过 2 幅二值图像的相关系数计算 ,
nwcr. .u et(a ,. m ,ades f m s d et h r tdi t e o v s dn td t a e td rs)r t nt ee . g l n ot n . o u w i n e D

hibernate常用方法

hibernate常用方法

hibernate常用方法Hibernate是一个开源的对象-关系映射框架,用于简化Java应用程序与数据库之间的交互。

Hibernate提供了丰富的API来执行通用的数据库操作,包括插入、更新、删除和查询。

下面是Hibernate常用的方法:1. save(:将一个新的对象插入到数据库中,返回一个唯一标识符。

2. update(:更新数据库中的一个对象。

3. delete(:从数据库中删除一个对象。

4. get(:根据给定的唯一标识符查询数据库中的一个对象。

5. load(:根据给定的唯一标识符查询数据库中的一个对象并加载它。

6. saveOrUpdate(:根据对象的状态来决定是插入还是更新数据库中的对象。

7. merge(:将给定对象的状态合并到数据库中的对象。

8. persist(:将一个新的对象插入到数据库中,并立即执行同步。

9. lock(:锁定一个对象,防止其他会话对其进行修改。

10. clear(:清除会话缓存中的所有对象。

11. evict(:从会话缓存中移除给定的对象。

12. refresh(:强制会话重新从数据库中加载对象的状态。

13. flush(:将会话缓存中的所有操作发送到数据库中。

14. Criteria API:用于创建复杂的查询条件。

15. HQL(Hibernate Query Language):类似于SQL的查询语言,用于查询对象。

16. Native SQL:直接执行SQL语句来操作数据库。

17. Transaction API:用于管理事务的开始、提交和回滚。

18. Session API:用于管理Hibernate会话的生命周期。

19. SessionFactory API:用于创建和销毁Hibernate会话工厂。

20. Dialect API:用于不同数据库间的差异性处理。

这些方法涵盖了Hibernate的核心功能,开发者可以根据具体的需求选择合适的方法来操作数据库。

基于Spring+Hibernate框架的农业信息化平台系统的设计与实现

基于Spring+Hibernate框架的农业信息化平台系统的设计与实现
收 稿 E期 :0 7( —1修 订 日期 :t 7I 7 t 2 0 32 ; 1 2) 4 1 0 )
维普资讯
第 5期
王可 : 于 S) n 基 1i l g+}t nae框 架的农 业 信息 化平 台系统的 设 计与 实现 I) l 1 c t
摘要: 集成 S r g与 Hi rae pi n b n t框架技术构建 基于 J E e 2 E的 We b应片可 以提 高 J E J 2 E项 目的可重用性 。介绍 了
使用技术 的原理及组合 Sr g Hbm t框架 的 We 应用。并给出在该框架 下设计 的农业信息 化平 台 系统的实 pn + i a i e e b
文 章 编号 :17 —7 2 2 0 0 一6 21 6 II4 (0 7)5I 2 5 ) 1
基 于 S rn +Hien t 架 的 农 业 信 息 化 平 台 p ig b r ae框 系统 的设 计 与 实现
王 可
( 西南 交通 大 学软 交换 实验 室 , 四川 成都 6 0 3 ) 10 1
的. E N T等 We b服务技 术体 系 。虽 然 JE 2 E为 基于 We b的企业应用提供 了优秀 的支持 , 面对 . E 但 . T的快速开发 , N
JE 2 E庞大的体系显得有些臃肿。与 JE 2 E重量级体系相对应, 在开发农业信息化平 台系统时引入了轻量级 We 框 b 架—一 Srg+Hi rae pi n b nt e 。这个轻量级 wl 框 架一方 面保持 了 JE e b 2 E的优势 , 另一方 面也简化 了 、e vb的开发 。
2 2 轻量 级 We 架概 述 . b框
针 对上述 问题 , 类似 于 S r g的轻量 级框 架 由此 产生 。所 谓的轻 量级 , pi n 并不 是 功能 弱 、 设计 简 陋 、 实现 粗糙 、

Hibernate的工作原理

Hibernate的工作原理

Hibernate的工作原理Hibernate是一个开源的Java持久化框架,它能够将Java对象映射到关系型数据库中,并提供了一套简单而强大的API,使得开辟人员能够更加方便地进行数据库操作。

Hibernate的工作原理主要包括以下几个方面:1. 对象关系映射(ORM):Hibernate使用对象关系映射技术将Java对象与数据库表之间建立起映射关系。

开辟人员只需要定义好实体类和数据库表之间的映射关系,Hibernate就能够自动地将Java对象持久化到数据库中,或者将数据库中的数据映射成Java对象。

2. 配置文件:Hibernate通过一个配置文件来指定数据库连接信息、映射文件的位置以及其他一些配置信息。

配置文件通常是一个XML文件,其中包含了数据库驱动类、连接URL、用户名、密码等信息。

开辟人员需要根据自己的数据库环境进行相应的配置。

3. SessionFactory:Hibernate的核心组件是SessionFactory,它负责创建Session对象。

SessionFactory是线程安全的,通常在应用程序启动时创建一次即可。

SessionFactory是基于Hibernate配置文件和映射文件来构建的,它会根据配置文件中的信息来创建数据库连接池,并加载映射文件中的映射信息。

4. Session:Session是Hibernate的另一个核心组件,它代表了与数据库的一次会话。

每一个线程通常会有一个对应的Session对象。

Session提供了一系列的方法,用于执行数据库操作,如保存、更新、删除、查询等。

开辟人员通过Session对象来操作数据库,而不直接与JDBC打交道。

5. 事务管理:Hibernate支持事务的管理,开辟人员可以通过编程方式来控制事务的提交或者回滚。

在Hibernate中,事务是由Session来管理的。

开辟人员可以通过调用Session的beginTransation()方法来启动一个事务,然后根据需要进行提交或者回滚。

hibernate 调用存储过程 传参 获取返回值

hibernate 调用存储过程 传参 获取返回值

Hibernate调用存储过程传参获取返回值简介Hibernate是一个流行的Java持久化框架,它提供了一种将Java对象映射到关系型数据库的方式。

在某些情况下,我们可能需要调用存储过程来执行一些复杂的数据库操作。

本文将介绍如何使用Hibernate调用存储过程,并传递参数和获取返回值。

准备工作在开始之前,我们需要完成以下准备工作:1.安装Java JDK和Hibernate框架。

2.配置Hibernate的数据库连接信息,包括数据库驱动、URL、用户名和密码等。

3.创建数据库存储过程,并确保它已经在数据库中正确地定义和测试。

Hibernate映射文件在使用Hibernate调用存储过程之前,我们需要创建一个Hibernate映射文件来定义存储过程的调用。

下面是一个示例的映射文件:<hibernate-mapping><sql-query name="callStoredProcedure" callable="true">{ call my_stored_procedure(:param1, :param2) }</sql-query></hibernate-mapping>在上面的示例中,我们定义了一个名为”callStoredProcedure”的SQL查询,其中”callable”属性被设置为”true”,表示这是一个调用存储过程的查询。

存储过程的调用语法是{ call procedure_name(:param1, :param2) },其中”:param1”和”:param2”是存储过程的输入参数。

调用存储过程一旦我们有了Hibernate映射文件,我们就可以在Java代码中使用Hibernate来调用存储过程。

下面是一个示例代码:Session session = HibernateUtil.getSessionFactory().getCurrentSession(); Transaction tx = session.beginTransaction();Query query = session.getNamedQuery("callStoredProcedure");query.setParameter("param1", value1);query.setParameter("param2", value2);query.executeUpdate();mit();在上面的示例中,我们首先获取Hibernate的Session对象,并开启一个事务。

hibernate注解简介

hibernate注解简介
在最近发布的几个Hibernate版本中,出现了一种基于 Java 5 注释的更为巧妙的新方法。借助新的 Hibernate Annotation 库,即可一次性地分配所有旧映射文件——一切都会按照您的想法来定义——注释直接嵌入到您的 Java 类中,并提供一种强大及灵活的方法来声明持久性映射。籍由自动代码完成和语法突出显示功能,最近发布的Java IDE也为其提供了有力的支持。
@Entity
@Table(name="T_MODEL_PLANE")
public class ModelPlane {
private Long id;
private String name;
@Id
@Column(name="PLANE_ID")
传统上,Hibernate的配置依赖于外部 XML 文件:数据库映射被定义为一组 XML 映射文件,并且在启动时进行加载。创建这些映射有很多方法,可以从已有数据库模式或Java类模型中自动创建,也可以手工创建。无论如何,您最终将获得大量的 Hibernate 映射文件。此外,还可以使用工具,通过javadoc样式的注释生成映射文件,尽管这样会给您的构建过程增加一个步骤。
...
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>3.2.1.ga</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>

hibernate query占位符参数循环处理

hibernate query占位符参数循环处理

hibernate query占位符参数循环处理(实用版)目录1.Hibernate 查询概述2.占位符参数3.循环处理4.实际应用示例正文1.Hibernate 查询概述Hibernate 是一款流行的 Java 框架,用于将数据库中的数据与Java 对象进行映射。

在 Hibernate 中,我们可以通过编写查询语句(Query)来实现对数据库的操作,例如查询、插入、更新和删除等。

2.占位符参数在编写查询语句时,我们常常需要将某些变量或表达式的值传递给查询,以便根据不同的条件来检索数据。

在 Hibernate 中,我们可以使用占位符参数(placeholder)来实现这一目的。

占位符参数用大括号{}表示,可以出现在查询语句的任何位置。

例如,我们可以编写一个简单的查询语句,根据传入的整数值来检索对应的用户信息:```javaString hql = "from User where age = {age}";```3.循环处理在某些场景下,我们需要处理多个占位符参数。

例如,假设我们需要根据传入的多个年龄值来检索符合条件的用户信息。

为了实现这一功能,我们可以使用循环来处理占位符参数。

以下是一个使用循环处理多个占位符参数的示例:```javaString hql = "from User where age in {ages}";List<Object> params = new ArrayList<>();params.add(18);params.add(25);params.add(30);// 将参数列表转换为占位符参数字符串String[] placeholders = new String[params.size()];for (int i = 0; i < params.size(); i++) {placeholders[i] = "{ages[" + i + "]}";}// 将占位符参数字符串添加到查询语句中hql = hql.replace("{ages}", String.join(", ", placeholders));```4.实际应用示例假设我们有一个 User 实体类,包含 id、name 和 age 属性。

Java 面试经典 04--Spring、Hibernate

Java 面试经典 04--Spring、Hibernate

Java 面试经典 04--Spring、Hibernate博客分类:javaSpringJava面试HibernateTomcatspring:依赖注入,事务管理,JDBC数据访问,spring中使用hibernate试题选择使用下面的Connection的哪个方法可以建立一个PreparedStatement接口( )A、 createPrepareStatement()B、 prepareStatement()C、 createPreparedStatement()D、 preparedStatement()考点:考察JDBC的api (B)在Jdbc中可以调用数据库的存储过程的接口是( )A、 StatementB、 PreparedStatementC、 CallableStatementD、 PrepareStatement 考点:考察JDBC的api (C)下面的描述正确的是( )A、 PreparedStatement继承自StatementB、 Statement继承自PreparedStatementC、 ResultSet继承自StatementD、 CallableStatement继承自PreparedStatement考点:考察JDBC的api (A)下面的描述错误的是( )A 、Statement的executeQuery()方法会返回一个结果集B、 Statement的executeUpdate()方法会返回是否更新成功的boolean值C、使用ResultSet中的getString()可以获得一个对应于数据库中char类型的值D、 ResultSet中的next()方法会使结果集中的下一行成为当前行考点:返回更新记录的id (B)如果数据库中某个字段为numberic型,可以通过结果集中的哪个方法获取( )A、 getNumberic()B、 getDouble()C、 setNumberic()D、 setDouble()考点:numberic是一种固定精度的浮点数 (B)在Jdbc中使用事务,想要回滚事务事务的方法是( )A、 Connection的commit()B、 Connection的setAutoCommit()C、 Connection的rollback()D、 Connection的close()考点:考察jdbc中的事务管理 (C)关于Class.forName()的作用,下列描述不正确的是:A、Class.forName(xxx.xx.xx);的作用是要求JVM查找并加载指定的驱动器类。

Spring试题和答案

Spring试题和答案

Spring考试试题1)下面关于Spring的说话正确的是(B C)(选择两项)A)Spring是一个重量级的框架B)Spring是一个轻量级的框架C)Spring是一个IOC和AOP容器D)Spring是一个入侵式的框架2)下面关于IOC的理解,正确的是(A B)(选择两项)A)控制反转B)对象被动的接受依赖类C)对象主动的去找依赖类D)一定要用接口3)下面关于AOP的理解,正确的是(B C)(选择两项)A)面向纵向的开发B)面向横向的开发C)AOP关注是面D)AOP关注的是点4)Spring的组成一共有(D)块组成。

A)1 B)3 C)5 D)75)Spring各模块之间关系(B C)(选择两项)A)Spring各模块之间是紧密联系的,相互依赖的B)Spring各模块之间可以单独存在C)Spring的核心模块是必须的,其他模块是基于核心模块D)Spring的核心模块不是必须的,可以不要6)Spring核心模块的作用(B)A)做AOP的B)做IOC的,用来管理Bean的C)是用来支持HiberneteD)是用来支持Struts的7)对Hibernate的支持主要用到Spring的那个模块(B)(选择两项)A)Spring核心模块B)Spring ORM模块C)Spring MVC模块D)Spring Web模块8)对Struts的支持主要用到Spring的那个模块(D)(选择两项)A)Spring核心模块B)Spring ORM模块C)Spring MVC模块D)Spring Web模块9)Spring的通知类型有(A B C D)(多项选择)A)Before通知B)After return通知C)Throws通知D)Around通知10)下面关于切入点的说法正确的是(A C D)(多项选择)A)是AOP中一系列连连接点的集合B)在做AOP时定义切入点是必须的C)在做AOP时定义切入点不是必须的D)可以用正则表达式来定义切入点11)Spring包装Hibernate之后的Hibernate的DAO应该继承那个类(C)A)HibernateDAOB)SessionFactoryC)HibernateDAOSuportD)Session12)下面对Spring包装Struts1.2的说法正确的是(B C)(选择两项)A)Spring包装Struts的ActionServletB)Spring包装Struts的ActionC)主要是利用Spring的依赖注入D)主要利用Spring的面向方面的编程13)Spring包装Struts时那些Spring模块是必须的(A D)(选择两项)A)Spring核心模块B)Spring AOP模块C)Spring MVC模块D)Spring WEB模块14)Spring中Before通知的目标对象要实现的接口是(A)A)MethodBeforeAdviceB)ThrowsAdviceC)AfterReturningAdviceD)MethodInterceptor15)Spring中around通知的目标对象要实现的接口是(D)A)MethodBeforeAdviceB)ThrowsAdviceC)AfterReturningAdviceD)MethodInterceptor16)Spring中Before通知的目标对象要实现的接口中before方法中的三个常用的参数依次是(A)A)方法,方法的参数,目标对象B)方法的参数,方法,目标对象C)目标对象,方法,方法的参数D)方法的参数,目标对象,方法17)Spring中around通知的目标对象要实现的接口中invoke中方法的参数是(C)A)方法B)目标对象C)方法执行参数D)Exception18)下面是Spring依赖注入方式的是(A B )(选择两项)A)set方法注入B)构造方法的注入C)get方法的注入D)接口的注入19)下面关于在Spring中配置Bean的id属性的说法正确的是(B D)(选择两项)A)id属性是必须,没有id属性就会报错B)id属性不是必须的,可以没有C)id属性的值可以重复D)id属性的值不可以重复20)下面关于在Spring中配置Bean的name属性的说法正确的是(B D)(选择两项)A)name属性是必须,没有name属性就会报错B)name属性不是必须的,可以没有C)name属性的值可以重复D)name属性的值不可以重复21)下面是IOC自动装载方法的是(A B)(选择两项)A)byNameB)byTypeC)constructorD)byMethod22)下面关于在Spring中配置Bean的init-method的说法正确的是(C)A)init-method是在最前面执行的B)init-method在构造方法后,依赖注入前执行C)init-method在依赖注入之后执行D)init-method在依赖注入之后,构造函数之前执行23)下面关于Spring配置文件说话正确的是(B C)(选择两项)A)Spring配置文件必须叫applicationContext.xmlB)Spring配置文件可以不叫applicationContext.xmlC)Spring配置文件可以有多个D)Spring配置文件只能有一个24)看下面的代码,说法正确的是(B)<bean id="userTable" class="erTable"><property name="userName"><value>ACCP</value></property></bean>A)其中<property name="userName">的userName是UserTable中的属性,可以不要get、set方法。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Spring and HibernateKen KousenWill ProvostVersion 2.0_3.2Spring+Hibernate. Spring and HibernateVersion 2.0_3.2Information in this document is subject to change without notice. Companies, names and data used in examples herein are fictitious unless otherwise noted. No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without the express written permission of the author.A publication of Capstone Courseware, LLC.877-227-2477© 2006-2007 Ken Kousen and Will Provost. All rights reserved.Published in the United States.This book is printed on 100% recycled paper.Introduction•This presentation illustrates the use of two popular frameworks in concert:−Spring – version 2.0−Hibernate – version 3.2•Though it may be interesting on its own (to those with experience in one or more of the above frameworks), we’ve built it primarily to compliment Capstone courses on these subjects.−It will be most effective as a sort of encore presentation at the end of a class that uses one or both of those courses.−It uses a build-and-deploy infrastructure similar to that found in the courses – merging some of the paths to JAR files is most of it. •We discuss each of these frameworks very briefly before addressing the issues involved in integrating them for Jara persistence tiers.Spring• The Spring Framework proposes to simplify and improve J2EE development, in a few key ways:− Its Core module provides a lightweight container for ordinary JavaBeans implements inversion of control (IoC ) anddependency injection , allowing complex graphs of objects to be declared rather than managed programmatically.− It simplifies exception handling by a combination of strategies: minimizing the use of checked exceptions, and providing anexcellent error reporting framework.− It offers a flexible web framework that implements themodel/view/controller pattern and offers pluggable strategies for all of its high-level decision-making.− It implements aspect-oriented programming at many levels, allowing “cross-cutting concerns” to be addressed effectively for even very complex applications.− It offers a simple means of integrating persistence tools whilepreserving application-level control of transactions.Hibernate•Hibernate is an open source project whose purpose is to make it easy to integrate relational data into Java programs.•This is done through the use of XML mapping files, which associate Java classes with database tables.•Hibernate provides basic mapping capabilities. It also includes several other object/relational mapping (ORM) capabilities, including:−An enhanced, object-based SQL variant for retrieving data, known as Hibernate Query Language (HQL).−Automated processes to synchronize objects with their database equivalents.−Built-in database connection pooling, including three open-source variants.−Transactional capabilities that can work both stand-alone or with existing Java Transaction API (JTA) implementations. •The goal of Hibernate is to allow object-oriented developers to incorporate persistence into their programs with a minimum of effort.Spring and Hibernate•Despite their conflicting seasonal allusions, these two frameworks can cooperate neatly within the persistence tier. •Hibernate can handle persistence more or less by itself.−It offers object/relational mapping.−It can manage sessions and transactions.•Spring brings a few nice features not found in Hibernate: −The IoC container makes configuring data sources, transaction managers, and DAOs easy.−It manages the Hibernate SessionFactory as a singleton – a small but surprisingly annoying task that must be implementedmanually when using Hibernate alone.−It offers a transaction system of its own, which is aspect-oriented and thus configurable, either through Spring AOP orJava-5 annotations. Either of these are generally much easierthan working with Hibernate’s transaction API.•As good as Hibernate is, Spring makes it a bit better.−You write less code.−Transaction management becomes nearly invisible for many applications, and where it’s visible, it’s still pretty easy.−You integrate more easily with other standards and frameworks.Configuring Hibernate Using Spring• A typical Hibernate application configures its SessionFactory using a properties file or an XML file.•First, we start treating that session factory as a Spring bean.−We declare it as a Spring <bean> and instantiate it using a Spring ApplicationContext.−We configure it using Spring<property>s, and this removes the need for a hibernate.cfg.xml or hibernate.properties file.−Spring dependency injection – and possibly autowiring – make short work of this sort of configuration task.•Hibernate object/relational mapping files are included as usual.•So we might write:<beanid="sessionFactory"class="org.hibernate.impl.SessionFactoryImpl"><propertyname="connection.driver_class"value="com.vendor.Driver"/><property name="connection.url" value="..." /><property name="show_sql" value="true" />...</bean>−... but we’re about to see that Spring offers a session factory for Hibernate that enables it to take advantage of AOP transactions.−So the code above is hypothetical: just a step in the right direction.Letting Spring Manage Transactions•To integrate Spring’s aspect-oriented transaction control with Hibernate’s ORM, Spring provides a special session factory, LocalSessionFactoryBean.−This and the rest of Spring’s Hibernate 3.x support are found in package org.springframework.orm.hibernate3.−This factory will create and manage proper Hibernate Session s, and also knows about Spring transactions.−It is configured through a set of properties that are closely related to the properties found in a Hibernate configuration file, though some names and data types are different.•Declare an instance of HibernateTransactionManager and inject the session factory into it.•Then define transactional advice on relevant persistent classes.−There are several ways to do this; we focus on the use of Java-5 annotations, meaning that the configuration will include theelement <tx:annotation-driven>.−Then individual persistent classes or (most likely) related DAOs will announce that they or some of their methods are@Transactional.•It’s essential that all these objects be instantiated through a Spring application context as managed beans.−Otherwise, there will be no AOP proxies and hence no “hook” for transaction control; everything else might work, but transactions would not be in force.Tools and Environment•The first code example runs on the following technology stack: −Java 5.0−MySQL 5.0−Hibernate 3.2•The second one is a web application and so brings in a few more players:−Tomcat 5.5−JSTL 1.1−Spring 2.0•Everything but the 5.0 JDK is bundled with the examples, in directories under c:/Capstone/Tools.•Be sure the environment includes these settings:−An environment variable CC_MODULE must be set toc:\Capstone\Spring+Hibernate.−The executable path must include the JDK’s bin directory and also c:/Capstone/Tools/Ant1.6/bin.MySQL and Tomcat•Start the MySQL RDBMS now, by running the following command from c:/Capstone/Tools/MySQL5.0/bin:mysqld−Note that the console you use to run this command will appear to hang; this is the MySQL daemon process listening for connections at its default port 3306.−When you want to shut the server down again, run this prepared script from the same directory:shutdown•Start the Tomcat server as well, by running the following script from c:/Capstone/Tools/Tomcat5.5/bin:startup−You’ll see a new console appear for the newly-started server process, and after a few seconds Tomcat will be initialized,showing a confirmation like this:INFO: Server startup in 6229 ms−When you want to shut down Tomcat, run this script from the same directory:shutdown•In c:/Capstone/Spring+Hibernate/Examples/Earthlings, the human-resources DAOs have been refit to work with Spring.•The ERD for the HR database is shown below:−See createdb.sql for the full DDL and DML that sets up this database for MySQL.•See the Spring configuration file src/DataSourceBeans.xml: −We declare a MySQL DataSource:<beanid="myDataSource" class="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" ><property name="url" value="jdbc:mysql://localhost/earthlings" /><property name="user" value="earthlings" /><property name="password" value="earthlings" /></bean>−The session factory depends on that and also on a set of Hibernate mapping files:<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"><property name="dataSource" ref="myDataSource" /> <property name="mappingResources"><list><value>cc/db/beans/Department.hbm.xml</value> <value>cc/db/beans/Location.hbm.xml</value><value>cc/db/beans/Employee.hbm.xml</value><value>cc/db/beans/Job.hbm.xml</value></list></property><property name="hibernateProperties"><value>hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialecthibernate.current_session_context_class=thread</value></property></bean>−We announce that our transactions are based on Java-5annotations, and establish a transaction manager:<tx:annotation-driventransaction-manager="myTxManager"/><bean id="myTxManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"><property name="sessionFactory"ref="mySessionFactory"/></bean>−Finally, we declare individual DAOs:<bean id="empDAO" class="cc.db.dao.EmployeeDAO"><property name="factory" ref="mySessionFactory" /> </bean><bean id="deptDAO" class="cc.db.dao.DepartmentDAO"> <property name="factory" ref="mySessionFactory" /> </bean><bean id="locDAO" class="cc.db.dao.LocationDAO"><property name="factory" ref="mySessionFactory" /> </bean><bean id="jobDAO" class="cc.db.dao.JobDAO"><property name="factory" ref="mySessionFactory" /> </bean><beanid="criteriaQueries"class="cc.db.hibernate.CriteriaQueries"autowire="byType"/>•With this configuration we have almost everything we need. •But, for this to work, we have to advise Spring’s transaction manager as to which methods should be transactional.−See src/cc/db/dao/EmployeeDao.java as an example of what all the DAO classes do:@Transactionalpublic class EmployeeDAO {private SessionFactory factory;public SessionFactory getFactory() {return factory;}public void setFactory(SessionFactory factory) { this.factory = factory;}@SuppressWarnings("unchecked")public List<Employee> findAll() {return factory.getCurrentSession().createCriteria(Employee.class).list();}...−The @Transactional annotation is recognized by the Spring transaction manager, and the session factory creates atransactional session for the duration of each method call.•Various console-application classes test the DAOs and Hibernate mappings.•The general modus operandi is to get an instance of a DAO from the Spring application context (which will be wired to all the session and transaction goodies), and start making method calls.−See src/cc/db/hibernate/PrintEmployees.java:public static void main(String[] args) {ApplicationContext context =new ClassPathXmlApplicationContext("DataSourceBeans.xml");EmployeeDAO eDAO =(EmployeeDAO) context.getBean("empDAO");List<Employee> emps = eDAO.findAll();for (Employee e : emps) {System.out.println(e.getLastName() +" has job " + e.getJob().getName());}}−src/cc/db/hibernate/CriteriaQueries.java works a little differently, instantiating itself as a sort of free-agent DAO that runs various queries that span entities, using a Hibernate Sessiondirectly.−For this to work, it too must be @Transactional, and so derives the current session from the session factory prior to carrying outCriteria API queries on that session.•Build and test the example as follows: −Create the database:createdb−Build the application:ant−Test various applications:run cc.db.hibernate.PrintEmployees Acosta has job ManagerAmdell has job Junior Engineer...Young has job TesterZimmerman has job Presidentrun cc.db.hibernate.PrintJobsrun cc.db.hibernate.PrintDepartments run cc.db.hibernate.PrintLocationsrun cc.db.hibernate.CriteriaQueries Conjunction:Walker Calhoun $38,000.00 MAHugh Campbell $32,000.00 MAKing Cardenas $84,000.00 NCMariana Castillo $67,000.00 NCTotal: 4...Number of employees in each department [32, GA][22, MA][46, NC][35, NJ]•Full results can be seen in ConsoleLog.txt.Using Hibernate in Spring Web Applications •It’s fairly simple to use Hibernate in a Java web application.−Hibernate session factories find configuration and mapping files on the class path, which makes it easy to assure that theseresources will be available at request time.−If data sources must be found by JNDI, there’s a little more work to do ... but then we’re going to assume Spring is in play.−The upcoming example uses a data-source bean configured directly for a Spring container, but Spring’s Java EE configuration schema provides a simple means of exposing a JNDI-named datasource as a bean, if necessary.• A “Spring MVC” web application declares its request-handling components – handler mapping, controllers, view resolver, views, and more – as Spring beans.•One or more of these beans – say, a given controller that’s responsible for carrying out some work on the database as its way of responding to an HTTP request – might depend on an injected Hibernate DAO.•From there, everything we’ve already seen obtains equally in the web-server process for the web application.−The DAO can be marked @Transactional.−The Spring/Hibernate session factory, once found by the web component(s), will take it from there.•In c:/Capstone/Spring+Hibernate/Wholesale is a web application that uses a Hibernate DAO to manage a single-table database of sales-feed information.•There are two configuration files.•docroot/WEB-INF/Wholesale-servlet.xml configures the web application itself.•There’s a lot here, but the connection to Hibernate is almost invisible, because ...−Various beans connect to the DAO by autowiring.−JSPs use a custom tag to look up the DAO for themselves.•But notice that this file imports docroot/WEB-INF/Database.xml.−This is almost identical in form to the configuration file in the previous example: data source, session factory, transactionmanager, and DAO.−It uses autowiring where the previous example didn’t.−It refers to just a single Hibernate mapping file, Order.hbm.xml.•The DAO class cc.sales.db.OrderDAOImplHibernate implements the interface cc.sales.OrderDAO.•This interface marks all three of its methods @Transactional, and so the implementing classes don’t need to.•Here’s the save method from this DAO:public void save(List<Order> feed, String feedName){Session session = getSession ();session.createQuery ("delete from Order ord " +"where ord.feed = :feedName") .setParameter ("feedName", feedName).executeUpdate ();for (Order order : feed){order.setFeed (feedName);session.save (order);}}−Note that this method leaves the data in an inconsistent state while in-process: it deletes all records for a given feed, and thenreconstructs them.−Transactionality will be very important here.•Build and test this application as follows:−Build the database:ant create-DB−Build and run a console application that primes the table with data:buildrun−Build and deploy the application:ant−Within 30 seconds you’ll see Tomcat detect the new context and install the application:INFO: Servlet 'Wholesale' configured successfully.−Visit the application at the following URL:http://localhost:8080/Wholesale−Click on Define feeds and choose one of the existing feeds to edit:−Choose the second order in the list, edit it so that it’s actually just more of the product shown in the first order – as shown below.This will violate a unique-key constraint in the database that says we can’t have more than one order for the same product in the same feed.−Click Edit Selected, and then click Done.•The fact that we get an exception here is not a failure of Spring or Hibernate (except perhaps in the sense that we could have some more user-friendly error reporting).•What we want to see is, did the data get corrupted when the user committed this error?−Visit the home page again, and navigate to the same feed you just edited.−You will see that it is safe and sound: the entire save operation was rolled back, thanks to a transaction that was put in play by Spring’s transaction manager for the Hibernate session used by the method.One Little Problem ...•Hibernate relies on a tool called CGLIB to generate proxy classes that monitor calls to persistent objects and thus serve as Hibernates “eyes and ears.”•CGLIB generates classes into an area known as the “PermGen” memory space.•Hibernate doesn’t explicitly clean up these generated proxies, and the PermGen space isn’t garbage-collected (because the Java VM assumes that it’s only for class information, which should be stable).•The result is a significant memory leak for certain uses of Hibernate.•Standalone applications rarely run into any trouble.•Web applications are another story: for Tomcat at least, repeated redeployment of a Hibernate-enabled web application will gradually drain the PermGen memory and halt the server!−This won’t be a problem for production environments with dedicated servers such that the server is stopped and restarted on a redeployment.−It is a major problem for developers who want to redeploy frequently, and for shared-server production environments.−There are many suggested fixes to this odd bug, but in our research we have yet to see any of them work.。

相关文档
最新文档