汤阳光Hibernate3.6(二)
- 格式:doc
- 大小:607.00 KB
- 文档页数:32
《J2EE系统架构和程序设计》课程设计实训项目——基于Struts +Spring +Hibernate架构的软件交易平台系统需求规格说明书1.1.1引言1、背景伴随着软件行业的蓬勃发展,越来越多的人以职业或非职业的身份进行着软件开发的工作,而其中不论是专业开发者还是软件爱好者,他们都会根据个人喜好,利用业余时间,开发一些或是极具有商业潜力(如:现如今非常有名的八十年代后戴志康的discuz 论坛),或是趣味无穷(如:韩国的flash 游戏企鹅系列),或是使用户得到无穷便利(如:某资深软件开发从业者的mail magic)的个人软件,我们可以将这些人统称为自由软件提供者。
源于方方面面的需要,人们对软件的需求越来越大,而专业的软件开发公司往往却不能满足人们的需求,这绝对不是认为如今的软件公司没有开发能力,恰恰相反这是这些正规公司开发能力很强,所以有些软件根本不会做,主要原因是利润太低,一个几k或者几十k的小项目对于一个专业公司来说真的是“食之无味”,对于处于上述状况的需求者我将其称为自由软件寻求者。
2、目的提供一个软件交易网络平台,集中买卖双方,系统提供自动匹配双方,用户自查询,多种交易方式等基本功能。
3、读者范围最终用户、软件设计人员。
4、定义(1)GB:中华人民共和国国家标准的英文缩写字母(2)构件:具有某种功能的可重用的软件模版单元,表示了系统中主要的计算元素和数据存储。
(3)逻辑视图:描述支持系统的功能需求的视图。
(4)开发视图:也称模块视图,主要侧重于软件模块的组织和管理描述。
5、参考资料(1)J2EE项目实训Hibernate框架技术(21世纪高等学校实用软件工程教育规划教材)杨少波编著清华大学出版社 2008 年5月(2)J2EE项目实训Spring框架技术(21世纪高等学校实用软件工程教育规划教材)杨少波编著清华大学出版社 2008 年5月(3)J2EE项目实训UML及设计模式(21世纪高等学校实用软件工程教育规划教材)杨少波编著清华大学出版社 2008 年5月(4)J2EE项目实训Struts框架技术(21世纪高等学校实用软件工程教育规划教材)杨少波编著清华大学出版社2008 年10月(5)《JSP与数据库连接》刘瑞挺,高等教育出版社(6)《数据库原理与方法》郑若忠王鸿武,湖南科学技术出版社(7)《软件需求》(美)Karl E.Wiegers 著,刘伟琴刘洪涛译1.1.2任务概述1、目标在本实训课结束时,使自己具有J2EE开发网站的经历,能够体会到用J2EE技术开发网站时需要注意的问题,并且懂得如何获取专业领域的知识的能力。
org.hibernate.exception.GenericJDBCException:。
异常信息:Exception:org.hibernate.exception.GenericJDBCException: could not execute statementStack trace:org.hibernate.exception.GenericJDBCException: could not execute statementat org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:136)at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2975)at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3487)at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:377)at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:214)at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:194)at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:178)at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:321)at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:286)at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:192)at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:206)at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:191)at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:764)at org.hibernate.internal.SessionImpl.save(SessionImpl.java:756)at org.hibernate.internal.SessionImpl.save(SessionImpl.java:752)at erDaoImpl.save(UserDaoImpl.java:19)at erServiceImpl.save(UserServiceImpl.java:16)at erServiceImpl$$FastClassByCGLIB$$7d9d4604.invoke(<generated>)at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:710)at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:643)at erServiceImpl$$EnhancerByCGLIB$$f1d51c6f.save(<generated>)at erAction.save(UserAction.java:26)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)at ng.reflect.Method.invoke(Method.java:606)at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:450)at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:289)at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:252)at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:167)at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265)at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138)at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:239)at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:239)at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:191)at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:73)at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:91)at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:252)at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145)at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171)at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:161)at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:193)at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:189) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:563)at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)at .JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)at ng.Thread.run(Thread.java:745)Caused by: java.sql.SQLException: Field 'id' doesn't have a default valueat com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1075)at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3566)at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3498)at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2113)at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2568)at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2113)at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2409)at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2327)at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2312)at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:133)... 105 more错误原因:没有设置数据库表主键⾃增长。
1.存储过程和存储函数1.1.存储过程与存储函数说明指存储在数据库中供所有用户程序调用的子程序叫存储过程、存储函数。
什么时候用存储过程/存储函数原则:如果只有一个返回值,用存储函数;否则,就用存储过程。
1.2.存储过程1.2.1.创建存储过程用CREATE PROCEDURE命令建立存储过程。
语法如下:create [or replace] PROCEDURE 过程名[(参数列表)]AS变量声明PLSQL子程序体;1.2.2.调用存储过程♦方法一:♦方法二:exec[ute] 存储过程名set serveroutput onexec raisesalary(7369);1.2.3.存储过程示例为指定的职工在原工资的基础上长10%的工资,并打印涨工资前和涨工资后的工资1.3.存储函数1.3.1.创建存储函数函数(Function)为一命名的存储程序,可带参数,并返回一计算值。
函数和过程的结构类似,但必须有一个RETURN子句,用于返回函数值。
函数说明要指定函数名、结果值的类型,以及参数类型等。
语法如下:CREATE [OR REPLACE] FUNCTION 函数名(参数列表)RETURN 函数值类型AS变量声明PLSQL子程序体;1.3.2.调用存储函数或写成:1.3.3.存储函数示例declarev_sal number;beginv_sal:=queryEmpSalary(7934);dbms_output.put_line('salary is:' || v_sal);end;/begindbms_output.put_line('salary is:' || queryEmpSalary(7934)); end;1.4.过程和函数中的in和out1.5.在Java语言中调用存储过程与存储函数1.5.1.JDBC调用存储过程●存储过程:●Java程序:1.5.2.JDBC调用存储函数●存储函数:●Java程序1.5.3.JDBC调用带光标类型out参数的存储过程或函数2.触发器2.1.说明●数据库触发器是一个与表相关联的、存储的PL/SQL程序。
第 3 期郭海洁, 等: Mg 3Y 2Ge 3O 12∶Pr 3+材料的多色发光及余辉性能图5(b )、(c )分别给出了Mg 3Y 2Ge 3O 12∶0.015Pr 3+样品在不同衰减时间下的余辉光谱和余辉衰减曲线。
可以看出,该材料的余辉衰减过程相对较快,在衰减1 200 s 后其强度仍然要比背底强度高,说明余辉的持续时间要比1 200 s 更长。
此外,如图5(c )插图所示,由于I -1与时间t 的函数关系可以拟合为一条直线,我们认为室温下余辉衰减较快的原因是由于电子从浅陷阱释放并且浅陷阱的浓度较低[28-29]。
为进一步研究不同激发波长对于余辉的充能效果,我们测试了Mg 3Y 2Ge 3O 12∶0.015Pr 3+的余辉激发光谱。
从图5(d )中可知,余辉的有效激发波长范围为215~320 nm ,最佳激发波长为 ~235 nm 。
与光致发光的激发波长相比,余辉 的有效激发波长对应的能量更高。
因此,在Mg 3Y 2Ge 3O 12∶Pr 3+材料中余辉充能的主要过程是电子吸收更高的能量从基态跃迁到导带,然后通过导带被陷阱捕获。
而光致发光的激发过程是电子在相对较低的能量激发下从基态跃迁到激发态能级,随后大部分激发态电子直接返回到基态产生发光现象。
3.5 热释光曲线分析为了进一步分析材料中的陷阱分布,我们进行了一系列热释光(TL )曲线测试。
TL 峰的强度代表了陷阱的浓度,TL 峰的位置表明了陷阱深度,TL峰的宽度反映了陷阱深度的分布[30-32]。
图6(a )给出了Mg 3Y 2Ge 3O 12以及Mg 3Y 2Ge 3O 12∶0.015Pr 3+的TL 曲线,插图为放大500倍后基质的TL 曲线。
可以看出,在Pr 3+掺入之后,TL 峰强度在高温区域有大幅度的提升,峰值温度为189 ℃,通过计算其对应的陷阱深度为~0.924 eV [33]。
图6(b )测试了系列样品Mg 3Y 2Ge 3O 12∶x Pr 3+经过254 nm 紫外光照射15 min 之后的TL 曲线。
The multi-angle view of MISR detects oil slicks under sun glitter conditionsGuillem Chust ⁎,Yolanda SagarminagaAZTI-Tecnalia,Marine Research Division,Herrera kaia portualdea z/g,20110Pasaia,Spain Received 15February 2006;received in revised form 4September 2006;accepted 9September 2006AbstractWe tested the use of the Multi-angle Imaging SpectroRadiometer (MISR)for detecting oil spills in the Lake Maracaibo,Venezuela,that were caused by a series of accidents between December 2002and March 2003.The MISR sensor,onboard the Terra satellite,utilises nine cameras pointed at fixed angles,ranging from nadir to ±70.5°.Based upon the Bidirectional Reflectance Factor,a contrast function and a classification accuracy assessment,it is shown,for two images examined under sun glint conditions,that the MISR sensor provides a better capability for oil spill discrimination,than the single-view MODIS-250m data.Analysis of the multi-angle MISR red band indicates that oil spills appear with greater contrast in those view angles affected by sun glitter as a result of local changes in surface roughness caused by the hydrocarbons.Although limited by cloud cover,the capability of the MISR instrument for oil spill discrimination,together with its weekly temporal resolution and open data access,have the potential for improving the operational monitoring of oil releases.©2006Elsevier Inc.All rights reserved.Keywords:Multi-angle view;MISR;Coastal zones;Oil spill;Sun glitter1.IntroductionThe anthropogenic release of oil into the oceans from tankers,ships and pipelines may have significant ecological and socioeconomic impacts on coastal environments.A substantial part of oil pollution originates from operative discharges from ships (European Space Agency,2002;Pavlakis et al.,1996).Early detection of accidental or deliberate oil spills can prevent serious damages on littoral habitats and assist in the identi-fication of polluters.At present,there exist multiple instruments capable of detecting oil spills (Bedborough,1996;Brekke &Solberg,2005;Fingas &Brown,2000;Fingas &Brown,1997;MacDonald et al.,1993),using both space and airborne platforms:radar (SAR,SLAR),UV,microwave radiometers,photographic cameras,video cameras,electro-optical sensors within the visible and infrared,and laser fluorosensors.As the studies of Fingas and Brown (2000)and Brekke and Solberg (2005)conclude,each instrument has strengths and deficien-cies,so there is no single instrument that is best at detecting spills but rather multiple sensors are needed to provide the best discrimination.Active sensors such as Synthetic ApertureRadar (SAR),have been used commonly for ocean pollution detection (e.g.DiGiacomo et al.,2004;Gade &Alpers,1999);they are preferred to optical sensors due to their all-weather and all-day capabilities (Brekke &Solberg,2005).However,SAR data have also several disadvantages:1)there is generally no daily sampling on a routine basis,2)their application to oil spill detection is limited to a small range of wind speed (1.5–6m/s,Liu et al.,2000;at high wind speeds,N 10m/s,few oil spills can be detected in the SAR images,Gade et al.,2000);likewise,the wind conditions can also limit the use of optical sensors since high winds mix the oil into the surface waters,thus removing its presence as a surface slick;3)features such as phytoplankton and freshwater slicks may have similar appearance as oil slicks on SAR,which results in ambiguous detection of the oil itself (Lin et al.,2002),and 4)the images may be expensive to purchase.Although optical sensors are affected by cloud cover,they have the advantage of permitting the discrimination between algal blooms and oil spills,based on multispectral information (Brekke &Solberg,2005).For instance,the Visible and Near Infrared (VNIR)bands of MODIS have been shown to be effective in detecting oil slicks in Lake Maracaibo,Venezuela (Hu et al.,2003),although oil reflects particularly well in the thermal infrared portion of the spectrum (Salisbury et al.,1993).Remote Sensing of Environment 107(2007)232–239⁎Corresponding author.Tel.:+34943004800;fax:+34943004801.E-mail address:gchust@pas.azti.es (G.Chust).0034-4257/$-see front matter ©2006Elsevier Inc.All rights reserved.doi:10.1016/j.rse.2006.09.024Remotely sensed land surface reflectance has been shown to depend upon changing sun and sensor viewing geometry.This dependence,termed the Bidirectional Reflectance Distribution Function(BRDF),is highly anisotropic for volumetric targets such as atmospheric aerosols and vegetation.Oceanographic features can also manifest anisotropy,and this phenomenon can be highlighted under sun glitter conditions.Sun glitter involves the direct reflection of sunlight from the water surface.The presence of glitter in an image has been considered often to represent a serious data loss.Conversely,the acquisition of imagery containing areas dominated by sun glitter can,in certain circumstances,be of considerable value(Khattak et al., 1991;MacDonald et al.,1993).This is the case of surface wind speed(Cox&Munk,1954),oceanic internal waves(Matthews, 2005),shallow water bottom topography(Hennings et al., 1994)and river plume frontal boundaries(Matthews et al., 1997).Furthermore,water surfaces affected by sun glitter often manifest brightness reversal between two different views,in which relatively bright features at one angle appear dark in the other view.Such a region of brightness reversal can be indica-tive of a locally rough or smooth surface texture(Matthews, 2005),this may be found,for example,in the surroundings of internal waves or ship wakes.The optical response of the state of the sea surface roughness can be described by either the BRDF,or by the contrast distribution function(Otremba& Piskozub,2001).The need for multi-view observations has led to the incorporation of such measurements in several spaceborne missions(Asner et al.,1998)such as the Advanced Spaceborne Thermal Emission and Reflection Radiometer(ASTER),Multi-angle Imaging SpectroRadiometer(MISR),POLarization and Directonality of the Earth's Reflectance(POLDER),and the Advanced Land Observing Satellite(ALOS).In this contribution,the use of the Multi-angle Imaging SpectroRadiometer(MISR)is compared to the MODIS bands, at250m,for detecting oil spills in Lake Maracaibo,a coastal lagoon connected to the Gulf of Venezuela.Between December 2002and March2003,oil companies operating in the Lake Maracaibo suffered a series of accidents,which led to extensive oil spills.The detection of oil marine pollutants by the MISR has not been investigated extensively;this is despite a short Note which appeared on this particular issue by the Jet Propulsion Laboratory(NASA,/ gallery/galhistory/2003_may_21.html).This omission is not surprising,since the multi-angle view of MISR was designed mainly for distinguishing different types of atmospheric particles(aerosols),cloud geometry,land surface covers,and for use in the construction of3-D models(Diner et al.,1998). Specifically,the questions addressed here are:which MISR view angles are the most appropriate to detect oil-contaminated waters?and at which sunlight conditions?Likewise,can the multi-angle measurements enhance the oil discrimination in relation to a single-angle optical imager?2.MISR and MODIS imagery of oil slicksThe MISR sensor consists of nine pushbroom cameras,one viewing the nadir(vertically downward)direction(designated An)and four each viewing the forward and backward directions along the spacecraft ground track,labelled Df,Cf,Bf,Af,and Aa,Ba,Ca,Da,respectively.The corresponding viewing zenith angles are:70.5°(Df,Da),60°(Cf,Ca),45.6°(Bf,Ba),26.1°(Af,Aa)and0°(An).The overall time delay,between the Df and Da cameras,is7min.It observes the Earth in four visible and near infrared(NIR)spectral bands(446,558,672,and 866nm),with a cross-track ground spatial resolution of275m–1.1km.Only images sampled at medium-resolution(275m) were used in this study,i.e.the red band(672nm)at all nine view angles,and the four spectral bands at nadir view.The MISR swath width is380km(cross-track).The operational data products from MISR are described in Bull et al.(2005).The medium-resolution MISR radiance imagery(Level 1B2),from1December2002to9March2003,has been examined for Lake Maracaibo(Fig.1).The location of spills in MISR images was extracted from the studies undertaken by the Jet Propulsion Laboratory(NASA),with MISR(/gallery/galhistory/2003_may_21.html);like-wise,by Hu et al.(2003)who had identified already oil spills in the Lake with MODIS-250m data,acquired on the same dates,and used airborne photography for ground truth.The spills dispersed in the Lake as an oil film floating on the surface. Of the19image sets available for this period(obtained from the NASA Langley Research Center Atmospheric Sciences Data Center),images were selected that were free of clouds.Amongst these images,the most apparent oil spill patches were visually identified in those collected during December2002and January 2003(26/12/02,4/01/03,20/01/03and27/01/03),using the 275-m resolution red band.Finally,multiple angle analysis was performed on the image sets acquired on26December2002and 20January2003(Fig.1),which presented several oil spills and optimal cloud cover conditions.The corresponding MODIS images acquired on these two dates have been analysed also,for comparative purposes.The MODIS sensor aboard the Earth Observing System(EOS) satellites Terra and Aqua,provides a morning and afternoon view with global,near-daily repeat coverage.Such data are distributed by the Land Processes Distributed Active Archive Center(U.S.Geological Survey Center for Earth Resources Observation and Science).The Level1B calibrated-radiances of MODIS band1(645nm,red)and band2(856nm,near infrared)were used.These bands have a spatial resolution of 250m.The MODIS swath width is2330km.The observational geometry parameters of the two selected dates involved in sun glitter conditions were contained in the corresponding products(the general conditions are described in Hennings et al.,1994,and in Matthews,2005).The geometric parameters are defined as follows(see also Bull et al.,2005). Solar zenith is the angle between the+z axis(which points into the earth,in the direction opposite the ellipsoid normal)and a vector anchored at the ground point extending into the earth in the direction of photon travel from the sun.Solar azimuth is the angle measured clockwise from the local north vector to the projection onto the x,y plane of the photon travel direction vector.This“photon travel azimuth”convention differs from the familiar“look azimuth”by180°.Camera zenith is the angle233G.Chust,Y.Sagarminaga/Remote Sensing of Environment107(2007)232–239between the −z axis and the “camera vector ”,which is anchored at the ground point and is directed toward the camera in the direction of photon travel.Camera azimuth is the angle measured clockwise from the local north vector to the projection onto the x ,y plane of the camera vector.For the images analysed,solar zenith (ζ)and azimuth (Φ)angles were:ζ=38.2°,Φ=330.9°(26/12/2002),and ζ=36.8°,Φ=324.5°(20/01/03).For Af view,the camera azimuth angles were 340.3°and 16.2°on 26/12/02and 20/01/03,respectively;the camera zenith angles were:30.1°and 28.5°on 26/12/02and 20/01/03,respectively.Near-surface wind speeds were low to moderate:4.4m/s (26/12/2002)and 5.6m/s (20/01/03);as measured byQuikSCATFig.1.Series of MISR (672nm)images of a portion of the Lake Maracaibo taken by cameras viewing 0°(camera An),26.1°forward (Af),and 45.6°forward (Bf).Black arrows on the An camera image indicate the oil spills used in the BRF analysis in the present paper;the white arrows indicate other main slicks used in the validation of supervised classifications.The inset image shows the location of Lake Maracaibo within the coastal region of the Gulf of Venezuela.234G.Chust,Y.Sagarminaga /Remote Sensing of Environment 107(2007)232–239(Level3Daily,0.25×0.25°Gridded Ocean Wind Vectors,JPL SeaWinds Project).These wind values fall within the range at which hydrocarbons dampen sea waves.3.Bidirectional reflectance factor and discrimination of oil slicksRadiance values were converted initially to the top-of-atmosphere bidirectional reflectance factor(BRF),for each band and view angle.The Bidirectional Reflectance Factor (BRF)is defined as the observed radiance divided by the radiance from a perfect Lambertian reflector,under conditions in which the illumination is from a single direction(Martonchik et al.,1998).We used the following equation to calculate the top-of-atmosphere BRF(see Bull et al.,2005):BRFð−l;l0;U−U0Þ¼p Lð−l;l0;U−U0Þd D2E0;b;where L is the measured radiance from MISR Level1B2radi-ance product,μis the cosine of viewing zenith angle,μ0is thecosine of solar zenith angle,Φ−Φ0is the difference betweensolar and viewing azimuth angles,D is the approximate dis-tance,in astronomical units,between the centre of the Earth andthe centre of the Sun,at the time that the MISR observes the firstpixel in the swath,and E std0,b(W m−2μm−1)is the standardised band-weighted solar irradiance.The BRF sampled within the oil slick patches and theirsurroundings(oil-free water)were analysed at different viewangles(i.e.9cameras)within the red band,and they have beencompared with glitter conditions and glitter angle.The BRFsamples were extracted by selecting visually all pixels withinthe oil slick patches,excluding boundary pixels,and unpollutedareas adjacent to each slick;one slick was chosen for each date(indicated in black arrows in Fig.1).The glitter conditions andglitter angle were contained in the corresponding productsdescribed in Bull et al.(2005),obtained also from the LangleyAtmospheric Data Center.Glitter conditions are represented bya binary mask image,providing a glitter contaminated/non-contaminated pixel information at1.1×1.1km.Glitter angle(°)is the angle between a vector from the observed point to thecamera and a vector pointing in the specular reflection direction;it is provided at17.6×17.6km spatial resolution.The potential discrimination of oil pollutants,using MISRand MODIS-250m,has been assessed by1)a comparison ofradiance means between oil slick patches and their surroundings(using a contrast function and the Wilks'Lambda test)for eachspectral band at nadir,and for each view angle;and2)super-vised classifications and the associated accuracy assessment.The contrast function(Otremba&Piskozub,2001),at a givenwavelengthλ,is expressed by the following relationship:cðf r;U r;kÞ¼L pðf r;U r;kÞ−L cðf r;U r;kÞL cðf c;U r;kÞwhere L p(ζr,Φr,λ)is the upward radiance above the polluted sea surface in a direction defined by a zenith angleζr and an azimuth angleΦr,and L c(ζr,Φr,λ)is the upward radiance above the clean sea surface.The Wilks'Lambda is based on a discriminant analysis and tests the hypothesis that the means are equal across classes(i.e.polluted vs clean waters).Wilks' Lambda close to0indicates that the classes are different.A per-pixel supervised classification method based on maximum likelihood algorithm was used to assess the discrimination between the oil slicks and two types of oil-free water.These two types of unpolluted waters have been defined to cover the maximal range in radiances on the water state of the Lake,at red wavelengths;thus,Type1refers to relatively high radiance values and Type2refers to relatively low radiances.Two independent training sites have been created;one to calculate the statistics needed for the classification;the other to evaluate the reliability of classifications.Several slicks for each date were used for classification(indicated in black and white arrows in Fig.1).Prior to performing the classification process,the Jeffries–Matusita separability index(Thomas et al.,1987)was calculated between pairs of classes using the first training site set.As measures of classification accuracy,the producer's accu-racy(PA)and the user's accuracy(UA)for each class,were used (Stehman,1997).These accuracy measurements are derived from the confusion matrix which is created from the comparison between the classification and the verification data(a set of training sites independent of that used for the classification process).Several classifications were performed combining those MISR bands and cameras with higher discrimination potential, based on the Wilks'Lambda test;likewise,one classification with MODIS(using NIR and red bands).4.Results and discussionFig.1shows a portion of the images at different view angles acquired by the275-m resolution MISR red band(672nm)of a part of Lake Maracaibo on26December2002and20January 2003.On these two dates,oil slicks were identified mainly in the three views affected mostly by sun glitter(Fig.2c,d):nadir, 26°and46°forward,i.e.An,Af and Bf cameras,respectively. At nadir and46°forward,all the oil slicks appear as darker zones on the image.At26°forward,which is the view closest to the specular reflection on the two dates(Fig.2c,d),the oil slick appears brighter on26December2002.On20January2003, where the glitter angle(29.8°)is not as close to the specular angle as on26December2002(10.9°),the slicks to the north and east appear darker,whilst the central slick is less visible.As previously shown,the differences in sun glitter conditions between the two dates depend mainly upon the different solar azimuth angle(Δ=6.4°)and Af camera azimuth angle (Δ=35.8°).Two large oil slicks,one for each date(indicated with black arrows in Fig.1),have been selected subsequently for analysis, to extract BRF values,contrast function and Wilks'Lambda. For December2002,Fig.2a shows that the differences in the BRF values are greater for the Af and Bf cameras,in which calm water regions are expected to be affected maximally by sun glitter(Fig.2c).At the An view,the oil has also an im-portant contrast value(Table1).The Wilks'Lambda provides slightly different results;it indicates that Bf is the camera within235G.Chust,Y.Sagarminaga/Remote Sensing of Environment107(2007)232–239the red band that better discriminates polluted waters,followed by An;whilst Af,the closest to the specular reflection,is not as capable as An and Bf.Although the Wilks'Lambda test indicates that slicks can be discriminated statistically on all of the cameras,those which are far from the specular reflection have less discrimination potential.For January 2003,the oil slick shows maximal BRF differences in the Af and An cameras,followed by Bf (Fig.2b);this is in accordance to the sun glitter conditions (Fig.2d),high contrast and low Wilks'Lambda values (Table 1).For the two dates,both the contrast and the Wilks'Lambda indicates that NIR is the most appro-priate,amongst the four VNIR spectral bands at nadir,to discriminate oil slicks,this is followed by the red band in most of the cases (Table 1).The red and the NIR bands of MODIS have similar values of contrast and Wilks'Lambda compared to the corresponding bands of MISR's An camera (Table 1).These results indicate that the direct reflection of sunlight arrives from the oil-contaminated water at 26°view on 26December 2002.The oil-contaminated waters in that date man-ifest brightness reversal between the moderately near specular angles (nadir and 46°forward-looking view)and the very-near specular angle (26°view).Such regions of brightness reversal can be indicators of local roughness changes in surface texture (Matthews,2005);and,as is well known,oil slicks tend to dampen surface capillary waves,making the water smoother than the surrounding oil-free water.As a general rule,the optical contrast of an oil film on a sea surface,at specific wind conditions and at red wavelengths,depends on three domains of the glitter angle:1)at angles (N 40°)not affected by sun glitter,slicks are practically not detected;2)at angles (b 15°)very near to the specular angle,the slicks appear brighter than the unpolluted areas;and 3)at angles (15°–40°)moderately near to the specular angle,the slicks appear darker,since oil is more absorbing than the surrounding water.This is the case for December 2002,whilst for January 2003a brightness reversal is not present,because of higher sun glitter angles (N 15°).The threshold values of glitter angles indicated here are obtained from the two images;in order to estimate these thresholds with confidence,more images are needed.Since An,Af,and Bf were identified as the cameras with high discrimination potential,four classifications were performed,combining these cameras with spectral bands at nadir:1)An view (NIR and red bands);2)An (NIR and red),Af and Bf;3)An (4bands),Af and Bf;and 4)An (NIR and red),and all cameras excluding Af.By comparing the first two classifications,the contribution of multi-angle with respect to just the An view is tested.The third classification tests the joint contribution of spectral bands with multi-angle view.By excluding Af,thefourthFig.2.The top-of-atmosphere BRF values from the MISR (672nm)image within the oil slicks on the Lake present on (a)26December 2002and (b)20January 2003,compared with the surrounding clean water at different view angles.Error bars represent ±standard deviation.For December 2002,the oil and unpolluted patches contained 307and 206pixels,respectively;for January 2003,the oil and unpolluted patches contained 15and 243pixels,respectively.The glitter angle and glitter condition of the area affected by spills at the corresponding dates:(c)26December 2002;and (d)20January 2003.236G.Chust,Y.Sagarminaga /Remote Sensing of Environment 107(2007)232–239classification tests the effect of removing brightness reversal in the image set of 2003.The Jeffries –Matusita index indicates high separability between oil and clean water Type 1in all cases at the two dates,including MODIS (Table 2).Conversely,low values of separability index were found between the oil and clean water Type 2,in two of the cases:using An (red and NIR)for MISR,and red and NIR for MODIS.The classification accuracy assessment (Table 2)has revealed that the two classifications combining Af and Bf cameras with spectral bands in An produced high values of producer's (PA)or user's accuracy (UA)(higher than 81%for December 2002and higher than 70%for January 2003).The classification using only the red and NIR bands in An produced low accuracy values (PA or UA inferior to 50%).These latter values are similar to the corresponding classification of the MODIS bands.The classification using all cameras excluding Af produced higher accuracy values for the December 2002(PA=65%and UA=75%)than that of MODIS (PA=53%and UA=30%).This observation indicates that the varying appearance of spills as a function of view angles alone (without the presence of brightness reversal)can improve oil discrimination in comparison to a single-view optical imager.However,the presence of brightness reversal,in particular,enhances this discrimination potential.In the case of January 2003,the classification using all cameras excluding Af produced a low producer's accuracy value (46%);once again,this indicates the importance of the Af camera in oil discrimination.The general low accuracy determinations in January 2003,compared with December 2002,is due to the absence of brightness reversal;likewise,to the size of the oil patches.In January 2003,the oil patch was small and thin and,hence,the radiance value is affected by the neighbouring pixels.5.Conclusions and perspectivesThe findings of the present study show,at least for the two images examined here,that the 275m resolution MISR sensor provides a capability for oil spill discrimination in coastal environments which is better than MODIS-250m sensor under sun glint.The results of the MISR red band,at different angle views,indicate that oil spills appear in more contrast in those views affected by sun glitter.The changes in the radiance-related quantities,as a function of view angle,depend on the composition,density,and geometric structure of the reflecting surface (i.e.water state);they are exemplified by glitters,shadows,and volumetric scattering (Diner et al.,2005).The results obtained here enable the conclusions to be reached that,spectrally,oil slicks can be detected within the red band;this contrast is highlighted under glitter conditions,as a result of local changes in surface roughness caused by the presence of hydrocarbons.Dampening of water surface waves by oil slicks occurs at low to moderate winds,which were the prevailing conditions on the two dates discussed here.For the two sets of images examined,three domains of oil radiometric response as a function of view angle have been identified:1)at angles unaffected by sun glitter,slicks were not identified or appeared slightly darker than adjacent unpolluted areas;2)at angles affected by sun glitter,but moderately near to the specular direction,slicks appeared darker because they are more absor-bent than unpolluted waters;and 3)at the specular angle,or very near to,the slicks appeared brighter.The specific range of sun glitter angles which dictates the radiometric contrast depend on wind speed conditions (Otremba &Piskozub,2001).This phenomenon is well established in SAR imagery,where the presence of hydrocarbon smoothes water surface roughness and causes a reduction in the backscattering.The detection of oceanic surface films by MISR depends on the factorsTable 2Jeffries –Matusita separability index and classification accuracies of oil slicks vs clean waters combining different bands and cameras of MISR and MODIS-250m (spills of 26December 2002and of 20January 2003).Key,PA:Producer's accuracy;UA:User's accuracy;Clean 1:oil-free water type 1;and Clean 2:oil-free water type 2(see text for explanation)SensorBands and camerasDecember 26,2002January 20,2003Jeffries –Matusita PA UA Jeffries –Matusita PA UA Oil vs Clean 1Oil vs Clean 2Oil Oil Oil vs Clean 1Oil vs Clean 2Oil Oil MISRAn (NIR,red)1.990.5449.7121.88 1.870.5347.5829.49An (NIR,red),Af,Bf2.00 1.9698.3793.30 1.99 1.4870.63100.0An (NIR,red,green,blue),Af,Bf2.00 2.0081.58100.0 1.99 1.9173.6194.29An (NIR,red),all cameras excluding Af 1.99 1.9665.2075.34 1.97 1.9945.7282.55MODISNIR,red1.990.7953.4429.531.880.5677.1748.76Table 1Contrast values and Wilks'Lambda test in oil slicks in relation to the surroundings waters,on 26December 2002and 20January 2003,for 275-m spatial resolution MISR and MODIS-250m SensorBandCameraDecember 26,2002January 20,2003ContrastWilks'Lambda Contrast Wilks'Lambda MISRBlue An −0.0170.135⁎⁎−0.0230.755⁎⁎Green An −0.0520.073⁎⁎−0.0430.937⁎⁎NIR An −0.1650.044⁎⁎−0.1780.571⁎⁎Red Df 0.0500.360⁎⁎−0.0080.995Red Cf 0.0270.240⁎⁎−0.0220.958⁎⁎Red Bf −0.1720.046⁎⁎−0.0490.919⁎⁎Red Af 0.4200.238⁎⁎−0.2050.504⁎⁎Red An −0.0920.056⁎⁎−0.1020.761⁎⁎Red Aa 0.0420.408⁎⁎−0.0070.998Red Ba 0.0220.412⁎⁎−0.0030.999Red Ca 0.0230.569⁎⁎−0.0050.997Red Da 0.0330.691⁎⁎−0.0080.985⁎MODIS-250mRed –−0.0930.095⁎⁎−0.0990.690⁎⁎NIR–−0.1930.091⁎⁎−0.2170.464⁎⁎⁎0.001b p b 0.05;where p is the p -value associated to the Wilks'Lambda test.⁎⁎p ≤0.001.237G.Chust,Y.Sagarminaga /Remote Sensing of Environment 107(2007)232–239。
基于Struts和Hibernate的图书管理系统设计与实现作者:唐昌华陈坚李洪亮来源:《中国管理信息化》2017年第20期[摘要]本文针对高校图书馆存在的问题,采用Struts和Hibernate技术设计实现图书管理系统,满足校园图书馆对图书管理的需求。
该系统采用B/S结构,使用JSP开发前台网页,后台使用Hibernate对Mysql数据库进行数据操作。
重点从总体框架、层次结构、数据库方面,对图书管理系统进行设计,并对系统进行测试,结果显示系统符合预期要求,提高了图书管理人员的工作效率。
[关键词]图书管理系统;Struts;Hibernatedoi:10.3969/j.issn.1673 - 0194.2017.20.095[中图分类号]G250.7 [文献标识码]A [文章编号]1673-0194(2017)20-0-020 引言本文设计并实现了图书管理系统,以能够完成图书、读者等基本信息的录入与查询,实现图书的借阅与归还,并能通过动态的权限分配,使管理人员拥有各自的功能管理,不互相影响,进而控制各级别管理人员不越权使用本系统。
1 Struts和Hibernate技术Struts是基于MVC(Model-View-Controller)设计模式的一个框架。
MVC设计模式,降低了数据处理和数据显示之间的耦合性,从而增强了程序的可复用性和易维护性。
Struts的处理过程如下。
(1)通过客户端JSP页面与用户进行交互,将页面提交的数据封装到Java Bean中。
(2)通过请求路径查找Struts.xml配置文件中Action的配置,找到并调用相应的Action。
(3)在Action中调用业务逻辑方法处理用户请求。
(4)查找相应的Result,并找到正确的JSP页面进行转发,返回给客户端。
Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,使Java程序员可以随心所欲地使用面向对象的思维方式,操作关系数据库。
1.1如何实现对Struts+Spring+Hibernate的SSH项目应用Mock方法实施单元测试的实例(第4部分)1.1.1体验TDD分层开发过程-----对前面的项目进行总装配1、将业务层与DAO层相互关联(装配业务层与DAO层)(1)修改UserLoginImple类中的doUserLogin方法package com.px1987.stcexample.model;import erInfoPO;import erManageDAOInterface;import erManageDAOJDBCImple;public class UserManageImple implements UserManageInterface{UserManageDAOInterface userManageDAOJDBCImple=null;public void setUserManageDAOJDBCImple( U serManageDAOInterface userManageDAOJDBCImple){ //本方法为后面的Spring做准备erManageDAOJDBCImple = userManageDAOJDBCImple;}public UserManageImple() {}public boolean doUpdateUserInfo(UserInfoEntityBean newUserInfo){ return false;}public boolean doUserLogin(UserInfoEntityBean loginUserInfo){boolean okOrNot=false;String userName=loginUserInfo.getUserName();String userPassWord=loginUserInfo.getUserPassWord();userManageDAOJDBCImple=new UserManageDAOJDBCImple();UserInfoPOreturnOneUserInfo=userManageDAOJDBCImple.SelectOneUserInfoData(userName,userPassWord);if(returnOneUserInfo!=null){okOrNot=true;}else{okOrNot=false;}return okOrNot;}public boolean doUserRegister(UserInfoEntityBean registerUserInfo) { return false;}}(2)测试装配是否成功----执行我们的测试套件并观察是否出现错误---我们要求的是,不应该出现错误!从上面的结果说明,我们的装配是正确。
第四章网上商城项目持久层设计和实现(第3/3部分)1.1.1构建对DAO组件进行单元测试的环境1、对基于Hibernate框架技术开发的组件的单元测试要点(1)测试主要涉及如下两个方面的测试1)对其hibernate.cfg.xml文件以及各个O/R Mapping 的*.xml文件2)基于hibernate的DAO组件中的各个数据访问功能的方法进行测试。
(2)在测试用例类中利用Configuration类中的configure()方法来定位被测试系统的hibernate.cfg.xml文件,从而获得SessionFactory,最后获得Session。
注意:有关对基于Hibernate框架技术开发的组件的单元测试具体详细的内容,请读者阅读本书的第九章“对基于Hibernate的DAO单元测试”的内容。
2、在当前项目所在的工作空间中添加一个测试项目(1)名称为TestWebShopProject选择【文件】菜单中的【新建】菜单,再选择【项目】菜单项,并选择【新建Java项目】菜单项后,将出现下面的图4.32所示的对话框。
在项目的名称输入框中输入项目名称为TestWebShopProject,请见下面的图4.32所示。
图4.32 添加测试项目TestWebShopProject的对话框(2)将前面的被测试项目引入到本测试项目中右击本测试项目名称,选择【属性】菜单,将出现下面的图4.33的项目属性对话框。
在“项目”标签页中点击【添加】按钮,最后在弹出的项目选择的对话框中选择前面的被测试项目的名称WebShopProject。
请参考下面的图4.33所示。
图4.33 将被测试项目引入到本测试项目中的对话框3、在本测试项目中添加JUnit的*.jar包文件右击本测试项目名称,选择【属性】菜单,将出现下面的图4.34的项目属性对话框。
在“库”标签页中点击【添加外部JAR(X)】按钮。
在本机器的磁盘中选择JUnit的系统包文件junit.jar(本项目采用JUnit 3.8版,当然本书假定读者熟悉单元测试以及JUnit单元测试的应用)。
1.Hibernate检索1.1.hibernate检索方式说明Hibernate 提供了以下几种检索对象的方式♦导航对象图检索方式: 根据已经加载的对象导航到其他对象♦OID 检索方式: 按照对象的OID 来检索对象♦HQL 检索方式: 使用面向对象的HQL 查询语言♦QBC 检索方式: 使用QBC(Query By Criteria) API 来检索对象. 这种API 封装了基于字符串形式的查询语句, 提供了更加面向对象的查询接口.♦本地SQL 检索方式: 使用本地数据库的SQL 查询语句1.2.HQL 检索方式HQL(Hibernate Query Language) 是面向对象的查询语言, 它和SQL 查询语言有些相似. 在Hibernate 提供的各种检索方式中, HQL 是使用最广的一种检索方式. 它有如下功能:♦在查询语句中设定各种查询条件♦支持投影查询, 即仅检索出对象的部分属性♦支持分页查询♦支持连接查询♦支持分组查询, 允许使用HA VING 和GROUP BY关键字♦提供内置聚集函数, 如sum(), min() 和max()♦能够调用用户定义的SQL 函数或标准的SQL 函数♦支持子查询♦支持动态绑定参数HQL检索方式包括以下步骤:♦通过Session 的createQuery() 方法创建一个Query 对象, 它包括一个HQL 查询语句. HQL 查询语句中可以包含命名参数♦动态绑定参数♦调用Query 的list() 方法执行查询语句. 该方法返回java.util.List 类型的查询结果, 在List 集合中存放了符合查询条件的持久化对象.Qurey 接口支持方法链编程风格, 它的setXxx() 方法返回自身实例, 而不是void 类型HQL vs SQL:♦HQL 查询语句是面向对象的, Hibernate 负责解析HQL 查询语句, 然后根据对象-关系映射文件中的映射信息, 把HQL 查询语句翻译成相应的SQL 语句. HQL 查询语句中的主体是域模型中的类及类的属性♦SQL 查询语句是与关系数据库绑定在一起的. SQL 查询语句中的主体是数据库表及表的字段.HQL的语法类似SQL语法。
1.2.1.绑定参数:♦Hibernate 的参数绑定机制依赖于JDBC API 中的PreparedStatement 的预定义SQL 语句功能.♦HQL 的参数绑定由两种形式:•按参数名字绑定: 在HQL 查询语句中定义命名参数, 命名参数以“:”开头.•按参数位置绑定: 在HQL 查询语句中用“?”来定义参数位置♦相关方法:•setEntity(): 把参数与一个持久化类绑定•setParameter(): 绑定任意类型的参数. 该方法的第三个参数显式指定Hibernate 映射类型绑定参数的形式,按参数名称绑定绑定参数的形式,按参数位置绑定1.2.2.使用别名通过HQL检索一个类的实例时,如果查询语句的其他地方需要引用它,应该为这个类指定一个别名from Customer as c where =:custnameas 可省略1.2.3.排序♦HQL 采用ORDER BY关键字对查询结果排序hql 查询:Query query = session.createQuery("from Customer c order by c.id");QBC查询:Criteria criteria = session.createCriteria(Customer.class);criteria.addOrder(org.hibernate.criterion.Order.asc(“id"));1.2.4.分页查询:♦setFirstResult(int firstResult): 设定从哪一个对象开始检索, 参数firstResult 表示这个对象在查询结果中的索引位置, 索引位置的起始值为0. 默认情况下, Query 从查询结果中的第一个对象开始检索♦setMaxResult(int maxResults): 设定一次最多检索出的对象的数目. 在默认情况下, Query 和Criteria 接口检索出查询结果中所有的对象1.2.5.投影查询♦投影查询: 查询结果仅包含实体的部分属性. 通过SELECT 关键字实现.♦Query 的list() 方法返回的集合中包含的是数组类型的元素, 每个对象数组代表查询结果的一条记录♦可以在持久化类中定义一个对象的构造器来包装投影查询返回的记录, 使程序代码能完全运用面向对象的语义来访问查询结果集.♦可以通过DISTINCT 关键字来保证查询结果不会返回重复元素使用构造函数1.2.6.分组与聚集函数报表查询用于对数据分组和统计, 与SQL 一样, HQL 利用GROUP BY关键字对数据分组, 用HA VING关键字对分组数据设定约束条件.在HQL 查询语句中可以调用以下聚集函数♦count()♦min()♦max()♦sum()♦avg()1.2.7.在映射文件中定义命名查询语句1.2.8.其他的查询动态查询:session.createCriteria(Customer.class).add(Expression.like(“name”,name.toLowerCase()),MatchMode.ANYWHERE).add(Expression.eq(“age”,new Int eger(11)));集合过滤:hql:createQuery(“from Order o where o.customer=:customer and o.price>100order by o.price”).setEntity(“customer”,customer).list();使用集合过滤:session.createFilter(customer.getOrders(),”where this.price > 100order by this.price”).list();子查询:from Customer c where 1 < (select count(o) from c.orders o);本地SQL查询:String sql=“select cs.ID as {c.id}, as {},cs.AGEas {c.age} from CUSTOMERS cs where cs.ID = 1”;Query query = session.createSQLQuery(sql,”c”,Customer.class);第二个参数是类的别名,在SQL语句中,每个字段的别名必须位于大括号内。
1.2.9.DML(数据操作语言)风格的操作,Hibernate 提供通过 Hibernate 查询语言(HQL)来执行大批量 SQL 风格的 DML 语句的方法。
UPDATE 和 DELETE 语句的伪语法为:( UPDATE | DELETE ) FROM? EntityName (WHEREwhere_conditions)?。
要注意的事项:•在 FROM 子句(from-clause)中,FROM 关键字是可选的•在 FROM 子句(from-clause)中只能有一个实体名,它可以是别名。
如果实体名是别名,那么任何被引用的属性都必须加上此别名的前缀;如果不是别名,那么任何有前缀的属性引用都是非法的。
•不能在大批量 HQL 语句中使用 joins 连接(显式或者隐式的都不行)。
不过在 WHERE 子句中可以使用子查询。
可以在 where 子句中使用子查询,子查询本身可以包含 join。
•整个 WHERE 子句是可选的。
使用Query.executeUpdate() 方法执行一个 HQL UPDATE语句由Query.executeUpdate() 方法返回的整型值表明了受此操作影响的记录数量Session session = sessionFactory.openSession();Transaction tx = session.beginTransaction();String hqlDelete = "delete Customer c where = :oldName";// or String hqlDelete = "delete Customer where name = :oldName";int deletedEntities = s.createQuery( hqlDelete ).setString( "oldName", oldName ).executeUpdate();mit();session.close();1.3.QBC 检索方式1.4.本地SQL 检索方式(了解)SQLQuery sqlquery = session.createSQLQuery("select {c.*} from CUSTOMERS c where"+" like :customerName and c.age=:customerAge");// 动态绑定参数sqlquery.setString("customerName", “%t%");sqlquery.setLong("customerAge", 21);“c”用来引用数据表的别名,例如以上代码中{c.*}表示使用c来作为customers表别名。
把sql查询返回的关系数据映射为对象sqlquery.addEntity("c", Customer.class);// 执行sql select语句,返回查询结果。
List list = sqlquery.list();1.5.简单的查询//使用hql查询Query query=session.createQuery("from Customer c where = 'tom1' ");List list=query.list();//使用qbc查询主要由Criteria、Criterion接口和Restrictions类组成,他支持在运行时动态生成查询语句。
Criteria criteria=session.createCriteria(Customer.class);//设定查询条件,每个Criterion实例代表一个查询条件Criterion cn1=Restrictions.eq("name", "tom1");criteria.add(cn1);list=criteria.list();//方法链编程:session.createCriteria(Customer.class).add(Restrictions.eq("name", "tom1")).list();1.6.HQL和QBC支持的各种运算1.6.1.小结2.事务和并发2.1. 数据库的隔离级别♦对于同时运行的多个事务, 当这些事务访问数据库中相同的数据时, 如果没有采取必要的隔离机制, 就会导致各种并发问题:•脏读: 对于两个事物 T1, T2, T1 读取了已经被 T2 更新但还没有被提交的字段. 之后, 若 T2 回滚, T1读取的内容就是临时且无效的.•不可重复读: 对于两个事物 T1, T2, T1 读取了一个字段, 然后 T2 更新了该字段. 之后, T1再次读取同一个字段, 值就不同了.•幻读: 对于两个事物 T1, T2, T1 从一个表中读取了一个字段, 然后 T2 在该表中插入了一些新的行. 之后, 如果 T1 再次读取同一个表, 就会多出几行. ♦数据库事务的隔离性: 数据库系统必须具有隔离并发运行各个事务的能力, 使它们不会相互影响, 避免各种并发问题.♦一个事务与其他事务隔离的程度称为隔离级别. 数据库规定了多种事务隔离级别, 不同隔离级别对应不同的干扰程度, 隔离级别越高, 数据一致性就越好, 但并发性越弱SQL ANSI SQL 标准定义了 4 种事务隔离级别,级别越高,成本越高:注:♦Oracle只支持 2 种事务隔离级别:READ COMMITED, SERIALIZABLE. Oracle 默认的事务隔离级别为: READ COMMITED♦Mysql 支持4中事务隔离级别。