JDBCSpring外文翻译
Spring中文翻译
Spring中⽂翻译Spring IoC 容器1.1 IoC Container 和 Bean 介绍控制反转(Inversion of Control,IoC )也被称为依赖注⼊(Dependency Injection,DI)。
这是⼀个,多个对象仅仅通过构造器参数,⼯⼚⽅法参数,或者对象实例在被构造器初始化或者被⼯⼚⽅法创建返回之后设置属性来定义它们之间的依赖关系(对象之间的调⽤关系)的过程。
容器在它创建 bean 之后,注⼊之间的依赖项。
这个过程和 bean 本⾝通过使⽤类的直接构造器或服务定位机制,来控制其依赖项的实例化或位置,基本上是相反的(因此被称为控制反转)。
由⼈为的new新建对象,⾃⾏控制对象的实例和调⽤关系,转为容器控制。
控制⽅发⽣改变所以是控制反转org.springframework.beans和org.springframework.context是 Spring IoC 容器的基础BeanFactory接⼝,提供了管理任何类型对象的⾼级配置机制ApplicationContext是BeanFactory的⼀个⼦接⼝。
补充更简单与 Spring 的 AOP 特性集成信息资源处理(⽤于国际化)事件发布应⽤层特定的上下⽂。
(例如WebApplicationContext在 Web 应⽤程序中的使⽤)简单的说,BeanFacotry提供了配置框架和基础功能。
ApplicationContext增加了更多的企业特定的功能。
ApplicationContext是BeanFactory的⼀个完整的超集。
在 Spring 中,构成应⽤程序主⼲并且被 Spring IoC 容器所管理的,被称为 beans。
⼀个 bean 是被 Spring IoC 容器实例化,组装和管理的⼀个对象。
不然,bean 仅仅只是你应⽤程序中众多对象中的⼀个。
Beans,之间的依赖关系由容器使⽤的配置元素据所体现。
Spring相关的外文文献和翻译(毕设论文必备)
附录1 外文原文Introducing the Spring FrameworkThe Spring Framework: a popular open source application framework that addresses many of the issues outlined in this book. This chapter will introduce the basic ideas of Spring and dis-cuss the central “bean factory”lightweight Inversion-of-Control (IoC) container in detail.Spring makes it particularly easy to implement lightweight, yet extensible, J2EE archi-tectures. It provides an out-of-the-box implementation of the fundamental architectural building blocks we recommend. Spring provides a consistent way of structuring your applications, and provides numerous middle tier features that can make J2EE development significantly easier and more flexible than in traditional approaches.The basic motivations for Spring are:To address areas not well served by other frameworks. There are numerous good solutions to specific areas of J2EE infrastructure: web frameworks, persistence solutions, remoting tools, and so on. However, integrating these tools into a comprehensive architecture can involve significant effort, and can become a burden. Spring aims to provide an end-to-end solution, integrating spe-cialized frameworks into a coherent overall infrastructure. Spring also addresses some areas that other frameworks don’t. For example, few frameworks address generic transaction management, data access object implementation, and gluing all those things together into an application, while still allowing for best-of-breed choice in each area. Hence we term Spring an application framework, rather than a web framework, IoC or AOP framework, or even middle tier framework.To allow for easy adoption. A framework should be cleanly layered, allowing the use of indi-vidual features without imposing a whole world view on the application. Many Spring features, such as the JDBC abstraction layer or Hibernate integration, can be used in a library style or as part of the Spring end-to-end solution.To deliver ease of use. As we’ve noted, J2EE out of the box is relatively hard to use to solve many common problems. A good infrastructure framework should make simple tasks simple to achieve, without forcing tradeoffs for future complex requirements (like distributed transactions) on the application developer. It should allow developers to leverage J2EE services such as JTA where appropriate, but to avoid dependence on them in cases when they are unnecessarily complex.To make it easier to apply best practices. Spring aims to reduce the cost of adhering to best practices such as programming to interfaces, rather than classes, almost to zero. However, it leaves the choice of architectural style to the developer.Non-invasiveness. Application objects should have minimal dependence on the framework. If leveraging a specific Spring feature, an object should depend only on that particular feature, whether by implementing a callback interface or using the framework as a class library. IoC and AOP are the key enabling technologies for avoiding framework dependence.Consistent configuration. A good infrastructure framework should keep application configuration flexible and consistent, avoiding the need for custom singletons and factories. A single style should be applicable to all configuration needs, from the middle tier to web controllers.Ease of testing. Testing either whole applications or individual application classes in unit tests should be as easy as possible. Replacing resources or application objects with mock objects should be straightforward.To allow for extensibility. Because Spring is itself based on interfaces, rather than classes, it is easy to extend or customize it. Many Spring components use strategy interfaces, allowing easy customization.A Layered Application FrameworkChapter 6 introduced the Spring Framework as a lightweight container, competing with IoC containers such as PicoContainer. While the Spring lightweight container for JavaBeans is a core concept, this is just the foundation for a solution forall middleware layers.Basic Building Blockspring is a full-featured application framework that can be leveraged at many levels. It consists of multi-ple sub-frameworks that are fairly independent but still integrate closely into a one-stop shop, if desired. The key areas are:Bean factory. The Spring lightweight IoC container, capable of configuring and wiring up Java-Beans and most plain Java objects, removing the need for custom singletons and ad hoc configura-tion. Various out-of-the-box implementations include an XML-based bean factory. The lightweight IoC container and its Dependency Injection capabilities will be the main focus of this chapter.Application context. A Spring application context extends the bean factory concept by adding support for message sources and resource loading, and providing hooks into existing environ-ments. Various out-of-the-box implementations include standalone application contexts and an XML-based web application context.AOP framework. The Spring AOP framework provides AOP support for method interception on any class managed by a Spring lightweight container. It supports easy proxying of beans in a bean factory, seamlessly weaving in interceptors and other advice at runtime. Chapter 8 dis-cusses the Spring AOP framework in detail. The main use of the Spring AOP framework is to provide declarative enterprise services for POJOs.Auto-proxying. Spring provides a higher level of abstraction over the AOP framework and low-level services, which offers similar ease-of-use to .NET within a J2EE context. In particular, the provision of declarative enterprise services can be driven by source-level metadata.Transaction management. Spring provides a generic transaction management infrastructure, with pluggable transaction strategies (such as JTA and JDBC) and various means for demarcat-ing transactions in applications. Chapter 9 discusses its rationale and the power and flexibility that it offers.DAO abstraction. Spring defines a set of generic data access exceptions that canbe used for cre-ating generic DAO interfaces that throw meaningful exceptions independent of the underlying persistence mechanism. Chapter 10 illustrates the Spring support for DAOs in more detail, examining JDBC, JDO, and Hibernate as implementation strategies.JDBC support. Spring offers two levels of JDBC abstraction that significantly ease the effort of writing JDBC-based DAOs: the org.springframework.jdbc.core package (a template/callback approach) and the org.springframework.jdbc.object package (modeling RDBMS operations as reusable objects). Using the Spring JDBC packages can deliver much greater pro-ductivity and eliminate the potential for common errors such as leaked connections, compared with direct use of JDBC. The Spring JDBC abstraction integrates with the transaction and DAO abstractions.Integration with O/R mapping tools. Spring provides support classes for O/R Mapping tools like Hibernate, JDO, and iBATIS Database Layer to simplify resource setup, acquisition, and release, and to integrate with the overall transaction and DAO abstractions. These integration packages allow applications to dispense with custom ThreadLocal sessions and native transac-tion handling, regardless of the underlyingO/R mapping approach they work with.Web MVC framework. Spring provides a clean implementation of web MVC, consistent with the JavaBean configuration approach. The Spring web framework enables web controllers to be configured within an IoC container, eliminating the need to write any custom code to access business layer services. It provides a generic DispatcherServlet and out-of-the-box controller classes for command and form handling. Request-to-controller mapping, view resolution, locale resolution and other important services are all pluggable, making the framework highly extensi-ble. The web framework is designed to work not only with JSP, but with any view technology, such as Velocity—without the need for additional bridges. Chapter 13 discusses web tier design and the Spring web MVC framework in detail.Remoting support. Spring provides a thin abstraction layer for accessing remoteservices without hard-coded lookups, and for exposing Spring-managed application beans as remote services. Out-of-the-box support is included for RMI, Caucho’s Hessian and Burlap web service protocols, and WSDL Web Services via JAX-RPC. Chapter 11 discusses lightweight remoting.While Spring addresses areas as diverse as transaction management and web MVC, it uses a consistent approach everywhere. Once you have learned the basic configuration style, you will be able to apply it in many areas. Resources, middle tier objects, and web components are all set up using the same bean configuration mechanism. You can combine your entire configuration in one single bean definition file or split it by application modules or layers; the choice is up to you as the application developer. There is no need for diverse configuration files in a variety of formats, spread out across the application.Spring on J2EEAlthough many parts of Spring can be used in any kind of Java environment, it is primarily a J2EE application framework. For example, there are convenience classes for linking JNDI resources into a bean factory, such as JDBC DataSources and EJBs, and integration with JTA for distributed transaction management. In most cases, application objects do not need to work with J2EE APIs directly, improving reusability and meaning that there is no need to write verbose, hard-to-test, JNDI lookups.Thus Spring allows application code to seamlessly integrate into a J2EE environment without being unnecessarily tied to it. You can build upon J2EE services where it makes sense for your application, and choose lighter-weight solutions if there are no complex requirements. For example, you need to use JTA as transaction strategy only if you face distributed transaction requirements. For a single database, there are alternative strategies that do not depend on a J2EE container. Switching between those transac-tion strategies is merely a matter of configuration; Spring’s consistent abstraction avoids any need to change application code.Spring offers support for accessing EJBs. This is an important feature (andrelevant even in a book on “J2EE without EJB”) because the use of dynamic proxies as codeless client-side business delegates means that Spring can make using a local stateless session EJB an implementation-level, rather than a fundamen-tal architectural, choice. Thus if you want to use EJB, you can within a consistent architecture; however, you do not need to make EJB the cornerstone of your architecture. This Spring feature can make devel-oping EJB applications significantly faster, because there is no need to write custom code in service loca-tors or business delegates. Testing EJB client code is also much easier, because it only depends on the EJB’s Business Methods interface (which is not EJB-specific), not on JNDI or the EJB API.Spring also provides support for implementing EJBs, in the form of convenience superclasses for EJB implementation classes, which load a Spring lightweight container based on an environment variable specified in the ejb-jar.xml deployment descriptor. This is a powerful and convenient way of imple-menting SLSBs or MDBs that are facades for fine-grained POJOs: a best practice if you do choose to implement an EJB application. Using this Spring feature does not conflict with EJB in any way—it merely simplifies following good practice.Introducing the Spring FrameworkThe main aim of Spring is to make J2EE easier to use and promote good programming practice. It does not reinvent the wheel; thus you’ll find no logging packages in Spring, no connection pools, no distributed transaction coordinator. All these features are provided by other open source projects—such as Jakarta Commons Logging (which Spring uses for all its log output), Jakarta Commons DBCP (which can be used as local DataSource), and ObjectWeb JOTM (which can be used as transaction manager)—or by your J2EE application server. For the same reason, Spring doesn’t provide an O/R mapping layer: There are good solutions for this problem area, such as Hibernate and JDO.Spring does aim to make existing technologies easier to use. For example, although Spring is not in the business of low-level transaction coordination, it does provide an abstraction layer over JTA or any other transaction strategy. Spring is alsopopular as middle tier infrastructure for Hibernate, because it provides solutions to many common issues like SessionFactory setup, ThreadLocal sessions, and exception handling. With the Spring HibernateTemplate class, implementation methods of Hibernate DAOs can be reduced to one-liners while properly participating in transactions.The Spring Framework does not aim to replace J2EE middle tier services as a whole. It is an application framework that makes accessing low-level J2EE container ser-vices easier. Furthermore, it offers lightweight alternatives for certain J2EE services in some scenarios, such as a JDBC-based transaction strategy instead of JTA when just working with a single database. Essentially, Spring enables you to write appli-cations that scale down as well as up.Spring for Web ApplicationsA typical usage of Spring in a J2EE environment is to serve as backbone for the logical middle tier of a J2EE web application. Spring provides a web application context concept, a powerful lightweight IoC container that seamlessly adapts to a web environment: It can be accessed from any kind of web tier, whether Struts, WebWork, Tapestry, JSF, Spring web MVC, or a custom solution.The following code shows a typical example of such a web application context. In a typical Spring web app, an applicationContext.xml file will reside in theWEB-INF directory, containing bean defini-tions according to the “spring-beans”DTD. In such a bean definition XML file, business objects and resources are defined, for example, a “myDataSource”bean, a “myInventoryManager”bean, and a “myProductManager”bean. Spring takes care of their configuration, their wiring up, and their lifecycle.<beans><bean id=”myDataSource”class=”org.springframework.jdbc. datasource.DriverManagerDataSource”><property name=”driverClassName”> <value>com.mysql.jdbc.Driver</value></property> <property name=”url”><value>jdbc:mysql:myds</value></property></bean><bean id=”myInventoryManager”class=”ebusiness.DefaultInventoryManager”> <property name=”dataSource”><ref bean=”myDataSource”/> </property></bean><bean id=”myProductManager”class=”ebusiness.DefaultProductManager”><property name=”inventoryManager”><ref bean=”myInventoryManager”/> </property><property name=”retrieveCurrentStock”> <value>true</value></property></bean></beans>By default, all such beans have “singleton”scope: one instance per context. The “myInventoryManager”bean will automatically be wired up with the defined DataSource, while “myProductManager”will in turn receive a reference to the “myInventoryManager”bean. Those objects (traditionally called “beans”in Spring terminology) need to expose only the corresponding bean properties or constructor arguments (as you’ll see later in this chapter); they do not have to perform any custom lookups.A root web application context will be loaded by a ContextLoaderListener that is defined in web.xml as follows:<web-app><listener> <listener-class>org.springframework.web.context.ContextLoaderListener </listener-class></listener>...</web-app>After initialization of the web app, the root web application context will beavailable as a ServletContext attribute to the whole web application, in the usual manner. It can be retrieved from there easily via fetching the corresponding attribute, or via a convenience method in org.springframework.web.context.support.WebApplicationContextUtils. This means that the application context will be available in any web resource with access to the ServletContext, like a Servlet, Filter, JSP, or Struts Action, as follows:WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(servletContext);The Spring web MVC framework allows web controllers to be defined as JavaBeans in child application contexts, one per dispatcher servlet. Such controllers can express dependencies on beans in the root application context via simple bean references. Therefore, typical Spring web MVC applications never need to perform a manual lookup of an application context or bean factory, or do any other form of lookup.Neither do other client objects that are managed by an application context themselves: They can receive collaborating objects as bean references.The Core Bean FactoryIn the previous section, we have seen a typical usage of the Spring IoC container in a web environment: The provided convenience classes allow for seamless integration without having to worry about low-level container details. Nevertheless, it does help to look at the inner workings to understand how Spring manages the container. Therefore, we will now look at the Spring bean container in more detail, starting at the lowest building block: the bean factory. Later, we’ll continue with resource setup and details on the application context concept.One of the main incentives for a lightweight container is to dispense with the multitude of custom facto-ries and singletons often found in J2EE applications. The Spring bean factory provides one consistent way to set up any number of application objects, whether coarse-grained components or fine-grained busi-ness objects. Applying reflection and Dependency Injection, the bean factory can host components that do not need to be aware of Spring at all. Hence we call Spring a non-invasiveapplication framework.Fundamental InterfacesThe fundamental lightweight container interface isorg.springframework.beans.factory.Bean Factory. This is a simple interface, which is easy to implement directly in the unlikely case that none of the implementations provided with Spring suffices. The BeanFactory interface offers two getBean() methods for looking up bean instances by String name, with the option to check for a required type (and throw an exception if there is a type mismatch).public interface BeanFactory {Object getBean(String name) throws BeansException;Object getBean(String name, Class requiredType) throws BeansException;boolean containsBean(String name);boolean isSingleton(String name) throws NoSuchBeanDefinitionException;String[] getAliases(String name) throws NoSuchBeanDefinitionException;}The isSingleton() method allows calling code to check whether the specified name represents a sin-gleton or prototype bean definition. In the case of a singleton bean, all calls to the getBean() method will return the same object instance. In the case of a prototype bean, each call to getBean() returns an inde-pendent object instance, configured identically.The getAliases() method will return alias names defined for the given bean name, if any. This mecha-nism is used to provide more descriptive alternative names for beans than are permitted in certain bean factory storage representations, such as XML id attributes.The methods in most BeanFactory implementations are aware of a hierarchy that the implementation may be part of. If a bean is not found in the current factory, the parent factory will be asked, up until the root factory. From the point of view of a caller, all factories in such a hierarchy will appear to be merged into one. Bean definitions in ancestor contexts are visible to descendant contexts, but not the reverse.All exceptions thrown by the BeanFactory interface and sub-interfaces extend org.springframework. beans.BeansException, and are unchecked. This reflects the fact that low-level configuration prob-lems are not usually recoverable: Hence, application developers can choose to write code to recover from such failures if they wish to, but should not be forced to write code in the majority of cases where config-uration failure is fatal.Most implementations of the BeanFactory interface do not merely provide a registry of objects by name; they provide rich support for configuring those objects using IoC. For example, they manage dependen-cies between managed objects, as well as simple properties. In the next section, we’ll look at how such configuration can be expressed in a simple and intuitive XML structure.The sub-interface org.springframework.beans.factory.ListableBeanFactory supports listing beans in a factory. It provides methods to retrieve the number of beans defined, the names of all beans, and the names of beans that are instances of a given type:public interface ListableBeanFactory extends BeanFactory {int getBeanDefinitionCount();String[] getBeanDefinitionNames();String[] getBeanDefinitionNames(Class type);boolean containsBeanDefinition(String name);Map getBeansOfType(Class type, boolean includePrototypes,boolean includeFactoryBeans) throws BeansException}The ability to obtain such information about the objects managed by a ListableBeanFactory can be used to implement objects that work with a set of other objects known only at runtime.In contrast to the BeanFactory interface, the methods in ListableBeanFactory apply to the current factory instance and do not take account of a hierarchy that the factory may be part of. The org.spring framework.beans.factory.BeanFactoryUtils class provides analogous methods that traverse an entire factory hierarchy.There are various ways to leverage a Spring bean factory, ranging from simple bean configuration to J2EE resource integration and AOP proxy generation. The bean factory is the central, consistent way of setting up any kind of application objects in Spring, whether DAOs, business objects, or web controllers. Note that application objects seldom need to work with the BeanFactory interface directly, but are usu-ally configured and wired by a factory without the need for any Spring-specific code.For standalone usage, the Spring distribution provides a tiny spring-core.jar file that can be embed-ded in any kind of application. Its only third-party dependency beyond J2SE 1.3 (plus JAXP for XML parsing) is the Jakarta Commons Logging API.The bean factory is the core of Spring and the foundation for many other services that the framework offers. Nevertheless, the bean factory can easily be usedstan-dalone if no other Spring services are required.附录2 中文译文Spring框架介绍Spring框架:这是一个流行的开源应用框架,它可以解决很多问题。
spring什么意思中文翻译_spring是什么意思
spring什么意思中文翻译_spring是什么意思大家认识spring这个单词吗?spring是英语常出现的一个单词,所以了解spring相关知识十分有必要,那么spring是什么意思呢?下面是小编给大家带来的spring是什么意思_spring的中文翻译,以供大家参考,我们一起来看看吧!目录spring是什么意思作名词:春天;春季;弹簧;弹力作动词:跳;弹;快速站起;突然提出spring的时态过去分词: sprung过去式: sprang现在分词: springingspring的英语例句1. I let the horse drop his head to crop the spring grass.我让马低下头啃吃春天的青草。
2. The blustery winds of spring had dropped to a gentle breeze.呼啸的春风已经减弱,成了习习的微风。
3. If unused, winter radishes run to seed in spring.如果不去动的话,冬萝卜会在春天开花结籽。
4. In the spring, the meadow is a mass of daffodils.春天,草地上开满了黄水仙。
5. And all the time next spring's elections are drawing closer.明年春天的选举即将来临。
6. I wouldn't lay bets on his still remaining manager after the spring.我看他的这个经理当不到春天之后了。
7. Freezing weather in spring hampered the hens' ability to lay.春天严寒的天气降低了母鸡的产蛋能力。
8. Every spring the ozone is chewed up, and the hole appears.每年春天,臭氧遭到破坏,空洞就出现了。
jdbctemplate方法详解
JdbcTemplate是Spring框架中提供的一个模板类,用于简化Java 应用程序与数据库之间的交互。
它提供了许多方便的方法,使得开发人员可以轻松地执行CRUD(创建、读取、更新和删除)操作。
以下是JdbcTemplate常用方法的详解:1. `getDataSource()`:返回与该模板关联的数据源。
2. `query(String sql, Object[] args, RowMapper<T> rowMapper)`:执行查询语句,返回结果集中的数据列表。
其中,sql是查询语句,args是查询参数的数组,rowMapper是将每一行数据映射为对象的映射器。
3. `queryForObject(String sql, Object[] args, RowMapper<T> rowMapper)`:执行查询语句,返回结果集中的第一行数据。
如果结果集为空,则返回null。
与`query()`方法类似,但只返回单个对象。
4. `update(String sql, Object[] args)`:执行更新语句,返回受影响的行数。
其中,sql是更新语句,args是更新参数的数组。
5. `update(String sql, Object[] args, int[] updateCounts)`:执行更新语句,返回受影响的行数数组。
其中,sql是更新语句,args是更新参数的数组,updateCounts是每个参数对应的受影响行数。
6. `execute(String sql, Object[] args, int[] updateCounts)`:执行任意类型的SQL语句(不只是更新语句),返回受影响的行数数组。
其中,sql是任意类型的SQL语句,args是参数的数组,updateCounts是每个参数对应的受影响行数。
7. `queryForList(String sql, Object[] args)`:执行查询语句,返回结果集中的数据列表。
spring的意思
spring的意思Spring的意思Spring是一种开源的、轻量级的、全栈的Java应用开发框架。
它是基于IoC(Inversion of Control)和AOP(Aspect-Oriented Programming)的编程模型,旨在简化企业级应用程序的开发。
首先,Spring的“意思”可以从字面上理解为春天的意思。
春天象征着新生、希望与活力。
同样,Spring框架为Java应用程序注入了新的活力与创造力,使得开发人员能够更加轻松地构建高效、可靠的应用程序。
Spring框架的核心特点是IoC和AOP:1. IoC(Inversion of Control):传统的编程模型中,应用程序的各个组件之间通常直接进行耦合。
而Spring采用IoC容器,将对象的依赖关系交由容器进行管理,通过配置文件或注解将对象之间的依赖关系进行解耦。
开发者只需关注业务逻辑的实现,而无需关心对象的创建和销毁,大大简化了开发流程。
2. AOP(Aspect-Oriented Programming):AOP是一种编程范式,与IoC相辅相成。
通过AOP,开发者可以将一些与业务逻辑无关但又需要在多个对象中复用的功能(如日志记录、性能监测等)进行横向抽取,并通过切面(Aspect)的方式进行集中管理。
Spring框架提供了强大的AOP支持,能够在不修改原有代码的情况下,动态地向程序中插入额外的功能。
Spring框架的设计理念是“面向接口编程”,它鼓励开发者通过接口定义业务逻辑,借助IoC容器将不同的实现进行组装。
这种松耦合的设计方式使得应用程序更加灵活、易于维护和扩展。
除了IoC和AOP,Spring框架还提供了许多其他功能和模块,方便开发者构建各种不同类型的应用程序:1. 数据访问层:Spring提供了对各种数据访问技术的支持,包括JDBC、ORM(如Hibernate)、NoSQL数据库等。
通过Spring的事务管理,开发者可以轻松地控制数据库事务,确保数据一致性。
Spring的web框架-外文翻译
英文原文Spring contains a lot of functionality and features, which are well-organized in seven modules shown in the diagram below. This section discusses each the of modules in turn.The Core package is the most fundamental part of the framework and provides the Dependency Injection features allowing you to manage bean container functionality. The basic concept here is the BeanFactory, which provides a factory pattern removing the need for programmatic singletons and allowing you to decouple the configuration and specification of dependencies from your actual program logic.On top of the Core package sits the Context package, providing a way to access beans in a framework-style manner, somewhat resembling a JNDI-registry. The context package inherits its features from the beans package and adds support for text messaging using e.g. resource bundles, event-propagation, resource-loading and transparent creation of contexts by, for example, a servlet container.The DAO package provides a JDBC-abstraction layer that removes the need to do tedious JDBC coding and parsing of database-vendor specific error codes. Also, the JDBC package provides a way to do programmatic as well as declarative transaction management, not only for classes implementing special interfaces, but for all your POJOs (plain old java objects).The ORM package provides integration layers for popular object-relational mapping APIs, including JDO, Hibernate and iBatis. Using the ORM package you can use all those O/R-mappers in combination with all the other features Spring offers, like simple declarative transaction management mentioned before.Spring's AOP package provides an AOP Alliance compliant aspect-oriented programming implementation allowing you to define, for example, method-interceptors and pointcuts to cleanly decouple code implementing functionality that should logically speaking be separated. Using source-level metadata functionality you can incorporate all kinds of behavioral information into your code, a little like .NET attributes.Spring's Web package provides basic web-oriented integration features, such as multipart functionality, initialization of contexts using servlet listeners and a web-oriented application context. When using Spring together with WebWork or Struts, this is the package to integrate with.Spring's Web MVC package provides a Model-View-Controller implementation for web-applications. Spring's MVC implementation is not just any implementation, it provides a clean separation between domain model code and web forms and allows you to use all the other features of the Spring Framework like validation.Spring's web MVC framework is designed around a DispatcherServlet that dispatches requests to handlers, with configurable handler mappings, view resolution, locale and theme resolution as well as support for upload files. The default handler is a very simple Controller interface, just offering a ModelAndView handleRequest(request,response) method. This can already be used for application controllers, but you will prefer the included implementation hierarchy, consisting of, for example AbstractController, AbstractCommandController and SimpleFormController. Application controllers will typically be subclasses of those. Note that youcan choose an appropriate base class: If you don't have a form, you don't need a FormController. This is a major difference to Struts.You can use any object as a command or form object -there's no need to implement an interface or derive from a base class. Spring's data binding is highly flexible, for example, it treats type mismatches as validation errors that can be evaluated by the application, not as system errors. So you don't need to duplicate your business objects' properties as Strings in your form objects, just to be able to handle invalid submissions, or to convert the Strings properly. Instead, it is often preferable to bind directly to your business objects. This is another major difference to Struts which is built around required base classes like Action and ActionForm - for every type of action.Compared to WebWork, Spring has more differentiated object roles. It supports the notion of a Controller, an optional command or form object, and a model that gets passed to the view. The model will normally include the command or form object but also arbitrary reference data. Instead, a WebWork Action combines all those roles into one single object. WebWork does allow you to use existing business objects as part of your form, but only by making them bean properties of the respective Action class. Finally, the same Action instance that handles the request is used for evaluation and form population in the view. Thus, reference data needs to be modeled as bean properties of the Action too. These are arguably too many roles for one object.Spring's view resolution is extremely flexible. A Controller implementation can even write a view directly to the response, returning null as ModelAndView. In the normal case, a ModelAndView instance consists of a view name and a model Map, containing bean names and corresponding objects (like a command or form, containing reference data). View name resolution is highly configurable, either via bean names, via a properties file, or via your own ViewResolver implementation. The abstract model Map allows for complete abstraction of the view technology, without any hassle. Any renderer can be integrated directly, whether JSP, V elocity, or any other rendering technology. The model Map is simply transformed into an appropriate format, such as JSP request attributes or a Velocity template model..Pluggability of other MVC implementationsThere are several reasons why some projects will prefer to use other MVC implementations. Many teams expect to leverage their existing investment in skills and tools. In addition, there is a large body of knowledge and experience avalailable for the Struts framework. Thus, if you can live with Struts' architectural flaws, it can still be a viable choice for the web layer. The same applies to WebWork and other web MVC frameworks.If you don't want to use Spring's web MVC, but intend to leverage other solutions that Spring offers, you can integrate the web MVC framework of your choice with Spring easily. Simply start up a Spring root application context via its ContextLoaderListener, and access it via its ServletContext attribute (or Spring's respective helper method) from within a Struts or WebWork action. Note that there aren't any "plugins" involved, so no dedicated integration is necessary. From the web layer's point of view, you'll simply use Spring as a library, with the root application context instance as the entry point.All your registered beans and all of Spring's services can be at your fingertips even withoutSpring's web MVC. Spring doesn't compete with Struts or WebWork in this scenario, it just addresses the many areas that the pure web MVC frameworks don't, from bean configuration to data access and transaction handling. So you are able to enrich your application with a Spring middle tier and/or data access tier, even if you just want to use, for example, the transaction abstraction with JDBC or Hibernate.Features of Spring MVCSpring's web module provides a wealth of unique web support features, including:Clear separation of roles - controller, validator, command object, form object, model object, DispatcherServlet, handler mapping, view resolver, etc. Each role can be fulfilled by a specialized object.Powerful and straightforward configuration of both framework and application classes as JavaBeans, including easy referencing across contexts, such as from web controllers to business objects and validators.Adaptability, non-intrusiveness. Use whatever controller subclass you need (plain, command, form, wizard, multi-action, or a custom one) for a given scenario instead of deriving from a single controller for everything.Reusable business code - no need for duplication. You can use existing business objects as command or form objects instead of mirroring them in order to extend a particular framework base class.Customizable binding and validation - type mismatches as application-level validation errors that keep the offending value, localized date and number binding, etc instead of String-only form objects with manual parsing and conversion to business objects.Customizable handler mapping and view resolution - handler mapping and view resolution strategies range from simple URL-based configuration, to sophisticated, purpose-built resolution strategies. This is more flexible than some web MVC frameworks which mandate a particular technique.Flexible model transfer - model transfer via a name/value Map supports easy integration with any view technology.Customizable locale and theme resolution, support for JSPs with or without Spring tag library, support for JSTL, support for Velocity without the need for extra bridges, etc.A simple but powerful tag library that avoids HTML generation at any cost, allowing for maximum flexibility in terms of markup code.Data Access using O/R MappersSpring provides integration with Hibernate, JDO, Oracle TopLink, Apache OJB and iBATIS SQL Maps: in terms of resource management, DAO implementation support, and transaction strategies. For example for Hibernate, there is first-class support with lots of IoC convenience features, addressing many typical Hibernate integration issues. All of these support packages for O/R mappers comply with Spring's generic transaction and DAO exception hierarchies. There are usually two integration styles: either using Spring's DAO 'templates' or coding DAOs against plain Hibernate/JDO/TopLink/etc APIs. In both cases, DAOs can be configured through DependencyInjection and participate in Spring's resource and transaction management.Spring's adds significant support when using the O/R mapping layer of your choice to create data access applications. First of all, you should know that once you started using Spring's support for O/R mapping, you don't have to go all the way. No matter to what extent, you're invited to review and leverage the Spring approach, before deciding to take the effort and risk of building a similar infrastructure in-house. Much of the O/R mapping support, no matter what technology you're using may be used in a library style, as everything is designed as a set of reusable JavaBeans. Usage inside an ApplicationContext does provide additional benefits in terms of ease of configuration and deployment; as such, most examples in this section show configuration inside an ApplicationContext.Some of the the benefits of using Spring to create your O/R mapping DAOs include:Ease of testing. Spring's inversion of control approach makes it easy to swap the implementations and config locations of Hibernate SessionFactory instances, JDBC DataSources, transaction managers, and mapper object implementations (if needed). This makes it much easier to isolate and test each piece of persistence-related code in isolation.Common data access exceptions.Spring can wrap exceptions from you O/R mapping tool of choice, converting them from proprietary (potentially checked) exceptions to a common runtime DataAccessException hierarchy. This allows you to handle most persistence exceptions, which are non-recoverable, only in the appropriate layers, without annoying boilerplate catches/throws, and exception declarations. You can still trap and handle exceptions anywhere you need to. Remember that JDBC exceptions (including DB specific dialects) are also converted to the same hierarchy, meaning that you can perform some operations with JDBC within a consistent programming model.General resource management. Spring application contexts can handle the location and configuration of Hibernate SessionFactory instances, JDBC DataSources, iBATIS SQL Maps configuration objects, and other related resources. This makes these values easy to manage and change. Spring offers efficient, easy and safe handling of persistence resources. For example: Related code using Hibernate generally needs to use the same Hibernate Session for efficiency and proper transaction handling. Spring makes it easy to transparently create and bind a Session to the current thread, either by using an explicit 'template' wrapper class at the Java code level or by exposing a current Session through the Hibernate SessionFactory (for DAOs based on plain Hibernate3 API). Thus Spring solves many of the issues that repeatedly arise from typical Hibernate usage, for any transaction environment (local or JTA).Integrated transaction management. Spring allows you to wrap your O/R mapping code with either a declarative, AOP style method interceptor, or an explicit 'template' wrapper class at the Java code level. In either case, transaction semantics are handled for you, and proper transaction handling (rollback, etc) in case of exceptions is taken care of. As discussed below, you also get the benefit of being able to use and swap various transaction managers, without your Hibernate/JDO related code being affected: for example, between local transactions and JTA, with the same full services (such as declarative transactions) available in both scenarios. As an additional benefit,JDBC-related code can fully integrate transactionally with the code you use to do O/R mapping. This is useful for data access that's not suitable for O/R mapping, such as batch processing or streaming of BLOBs, which still needs to share common transactions with O/R mapping operations.To avoid vendor lock-in, and allow mix-and-match implementation strategies. While Hibernate is powerful, flexible, open source and free, it still uses a proprietary API. Furthermore one could argue that iBA TIS is a bit lightweight, although it's excellent for use in application that don't require complex O/R mapping strategies. Given the choice, it's usually desirable to implement major application functionality using standard or abstracted APIs, in case you need to switch to another implementation for reasons of functionality, performance, or any other concerns. For example, Spring's abstraction of Hibernate transactions and exceptions, along with its IoC approach which allows you to easily swap in mapper/DAO objects implementing data access functionality, makes it easy to isolate all Hibernate-specific code in one area of your application, without sacrificing any of the power of Hibernate. Higher level service code dealing with the DAOs has no need to know anything about their implementation. This approach has the additional benefit of making it easy to intentionally implement data access with a mix-and-match approach (i.e. some data access performed using Hibernate, and some using JDBC, others using iBATIS) in a non-intrusive fashion, potentially providing great benefits in terms of continuing to use legacy code or leveraging the strength of each technology.The Spring transaction abstractionSpring provides a consistent abstraction for transaction management. This abstraction is one of the most important of Spring's abstractions, and delivers the following benefits: Provides a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, iBA TIS Database Layer and JDO.Provides a simpler, easier to use, API for programmatic transaction management than most of these transaction APIsIntegrates with the Spring data access abstractionSupports Spring declarative transaction managementTraditionally, J2EE developers have had two choices for transaction management: to use global or local transactions. Global transactions are managed by the application server, using JTA. Local transactions are resource-specific: for example, a transaction associated with a JDBC connection. This choice had profound implications. Global transactions provide the ability to work with multiple transactional resources. (It's worth noting that most applications use a single transaction resource) With local transactions, the application server is not involved in transaction management, and cannot help ensure correctness across multiple resources.Global transactions have a significant downside. Code needs to use JTA: a cumbersome API to use (partly due to its exception model). Furthermore, a JTA UserTransaction normally needs to be obtained from JNDI: meaning that we need to use both JNDI and JTA to use JTA. Obviously all use of global transactions limits the reusability of application code, as JTA is normally only available in an application server environment.The preferred way to use global transactions was via EJB CMT (Container Managed Transaction): a form of declarative transaction management (as distinguished from programmatic transaction management). EJB CMT removes the need for transaction-related JNDI lookups--although of course the use of EJB itself necessitates the use of JNDI. It removes most--not all--need to write Java code to control transactions. The significant downside is that CMT is (obviously) tied to JTA and an application server environment; and that it's only available if we choose to implement business logic in EJBs, or at least behind a transactional EJB facade. The negatives around EJB in general are so great that this is not an attractive proposition, when there are alternatives for declarative transaction management.Local transactions may be easier to use, but also have significant disadvantages: They cannot work across multiple transactional resources, and tend to invade the programming model. For example, code that manages transactions using a JDBC connection cannot run within a global JTA transaction.Spring resolves these problems. It enables application developers to use a consistent programming model in any environment. You write your code once, and it can benefit from different transaction management strategies in different environments. Spring provides both declarative and programmatic transaction management. Declarative transaction management is preferred by most users, and recommended in most cases.With programmatic transaction management developers work with the Spring transaction abstraction, which can run over any underlying transaction infrastructure. With the preferred declarative model developers typically write little or no code related to transaction management, and hence don't depend on Spring's or any other transaction API.中文译文Core包是框架的最基础部分,并提供依赖注入(Dependency Injection)特性来使你可管理Bean容器功能。
spring中几个英文单词
zero_exception exception;
v_num1 number;
v_num2 number;
v_result number;
begin
v_num1 :=10;
v_num2 :=0;
if v_num2=0 then
raise zero_exception;
aspect :切面
joinPoint:加入点
pointCut:切入点
advice :说明在开始事务后还是开启事务前执行,提示拦截器
target 目标对象 w Nhomakorabeaave:植入事务
proxy:代理对象,在开启事务前执行,或关闭事务后执行
spring通过2中方式产生代理:jdk动态代理
为了同步开始,使用conn=DataSourceUtils.getConnection(dataSource);
traintent 对象序列化,而被此修饰的不参与序列
-----------------------------
pl/sql
set serveroutput on
代理对象,对象接口,对象拦截器
jdck动态代理:不需要实现任何接口
用tx:advice的方法配置拦截器
`requires_new无论有么有事务都建新的事务
isolation="defalut" 解决脏读
定义切点,把切面植入到切点上面
end;
select distinct object_name,object_type from user_objects;
create or replace procedure proc_hello(name varchar2)
Spring框架-毕业论文外文文献翻译
外文文献翻译SpringFrameworkSpring is an open source framework, and Spring was launched in 2003 as a lightweight Java development framework created by Rod Johnson.In a nutshell, Spring is a hierarchical, JavaSE/EEfull-stack (one-stop) lightweight open source framework.The powerful JavaBeans based configuration management using the Inversion of Control (IoC) principle makes application components faster and easier.1.facilitate decoupling and simplify developmentThrough the IoC container provided by Spring, we can control dependencies between objects by Spring, avoiding excessive program coupling caused by hard coding.With Spring, users do not have to write code for the bottom tier requirements of single instance schema classes, properties, file parsing, and so on, and can focus more on top tier applications.2.AOP programming supportThrough the Spring functionality provided by AOP, it is easy to implement face oriented programming, and many features that are not easily implemented with traditional OOP can be easily handled by AOP.3.declarative transaction supportIn Spring, we can extricate ourselves from tedious and tedious transaction management code and flexibly manage the transaction through declarative manner, so as to improve the efficiency and quality of development.4.convenience program testingAlmost all test work can be done in a non container dependent programming manner, and in Spring, testing is no longer expensive, but something to do.For example, Spring supports Junit4 and can easily test Spring programs by annotations.5.convenient integration of various excellent frameworkSpring does not exclude all kinds of excellent open source framework, on the contrary, Spring can reduce the difficulty of the use of Spring framework, provides a framework for a variety of excellent (such as Struts, Hibernate, Hessian, Quartz) directly support the.6.reduce the difficulty of using Java EE APISpring provides a thin layer of encapsulation for many difficult Java, EE, API (such as JDBC, JavaMail, remote calls, etc.), and the use of these Java EE API is greatly reduced through the simple package of Spring.7.Java source code is a classic example of learningSpring source code, clear structure, exquisite design originality, embodies the master of the Java design pattern and the flexible use of Java technology accomplishment.Spring framework source code is undoubtedly the best practice example of Java technology.If you want to quickly improve your Java skills and application development level in a short time, learning an.The role of MVC - Spring is integration, but not just integration, and the Spring framework can be seen as a framework for enterprise solution levels.The client sends a request, the server controller (implemented by DispatcherServlet) to complete the request forwarding, call a controller for mapping class HandlerMapping, the class is used to map requests to the corresponding processor to process the request.HandlerMapping will request is mapped to the corresponding processor Controller (equivalent to Action) in Spring if you write some processor components, the general implementation of the Controller interface in Controller, you can call Service or DAO to operate data from the DAO ModelAndView used to store the retrieved data, some data can also be stored in response to the view.If you want to return the result to the user, it also provides a view of ViewResolver component in Spring framework, the component labeled Controller returns according to, find the corresponding view, the response response back to the user.Each module (or component) that makes up the Spring framework can exist alone, or can be implemented in conjunction with one or more other modules.Each module has the following functions: 1, the core container: the core container provides the basic functionality of the Spring framework (Spring, Core).The main component of the core container is BeanFactory, which is implemented in factory mode.BeanFactory uses the control inversion (IOC) pattern to separate application configuration and dependency specifications from theactual application code.Spring框架Spring是一个开源框架, Spring是于2003 年兴起的一个轻量级的Java 开发框架, 由Rod Johnson创建。
JDBC接口技术外文文献翻译、中英文翻译、外文翻译
外文出处:《Exploiting Software How to Break Code》By Greg Hoglund, Gary McGraw Publisher : Addison Wesley Pub Date : February 17, 2004ISBN : 0-201-78695-8译文标题:JDBC接口技术译文:JDBC是一种可用于执行SQL语句的JavaAPI(ApplicationProgrammingInterface应用程序设计接口)。
它由一些Java语言编写的类和界面组成。
JDBC为数据库应用开发人员、数据库前台工具开发人员提供了一种标准的应用程序设计接口,使开发人员可以用纯Java语言编写完整的数据库应用程序。
一、ODBC到JDBC的发展历程说到JDBC,很容易让人联想到另一个十分熟悉的字眼“ODBC”。
它们之间有没有联系呢?如果有,那么它们之间又是怎样的关系呢?ODBC是OpenDatabaseConnectivity的英文简写。
它是一种用来在相关或不相关的数据库管理系统(DBMS)中存取数据的,用C语言实现的,标准应用程序数据接口。
通过ODBCAPI,应用程序可以存取保存在多种不同数据库管理系统(DBMS)中的数据,而不论每个DBMS使用了何种数据存储格式和编程接口。
1.ODBC的结构模型ODBC的结构包括四个主要部分:应用程序接口、驱动器管理器、数据库驱动器和数据源。
应用程序接口:屏蔽不同的ODBC数据库驱动器之间函数调用的差别,为用户提供统一的SQL编程接口。
驱动器管理器:为应用程序装载数据库驱动器。
数据库驱动器:实现ODBC的函数调用,提供对特定数据源的SQL请求。
如果需要,数据库驱动器将修改应用程序的请求,使得请求符合相关的DBMS所支持的文法。
数据源:由用户想要存取的数据以及与它相关的操作系统、DBMS和用于访问DBMS的网络平台组成。
虽然ODBC驱动器管理器的主要目的是加载数据库驱动器,以便ODBC函数调用,但是数据库驱动器本身也执行ODBC函数调用,并与数据库相互配合。
JDBC_SpringJDBC_MyBatis性能比较
Write
次序
循环次数
JDBC
JDBC.Object
Spring.JDBC
MyBatis
JDBC
JDBC.Object
Spring.JDBCMyBFra bibliotektis1
50
1922
2136
2113
3150
1193
1217
1620
1622
2
100
4303
4379
4377
5349
2105
2200
3296
3204
37.996
43.49333333
综合比较图:
结论:
JDBC > JDBC.Object > Spring.JDBC > MyBatis
测试目的:
比较JDBC,SpringJdbc和MyBatis的性能。
测试用例:
1.查询:查询一张10000条数据的表,只取前1000条
2.更新:对该表分别进行:
a)插入一条数据
b)更新一条数据
c)删除一条数据
3.测试项:
a)JDBC:纯粹jdbc代码
b)JDBC.Object:jdbc的结果集转化为Object对象
10133
11506
14834
14115
11
550
23331
23942
23987
29032
11605
12918
15966
15797
Read对比图:
Write对比图:
综合比较:
read和write值由上面表格平均得到,即read[JDBC]=sum(read[JDBC])/sum(循环次数)
springjdbc查询结果返回对象、对象列表
springjdbc查询结果返回对象、对象列表⾸先,需要了解spring jdbc查询时,有三种回调⽅式来处理查询的结果集。
可以参考,写得还不错。
1.返回对象(queryForObject)有两种办法,即两个容易混淆的⽅法://1public Object queryForObject(String sql, Map<String, ?> paramMap, RowMapper rowMapper) {...}//2public Object queryForObject(String sql, Map<String, ?> paramMap, Class requiredType) {...}第⼀种⽅法是需要⼀个实现了RowMapper接⼝的对象实例作为第三个参数,实现RowMapper接⼝的类如下(其中类User.java有id、username、password、dept四个属性。
):public class UserRowMapper implements RowMapper<User>{@Overridepublic User mapRow(ResultSet rs, int rowNum) throws SQLException {User user = new User();user.setId(rs.getInt(1));user.setUsername(rs.getString(2));user.setPassword(rs.getString(3));user.setDept(4);return user;}}UserRowMapper.java类在dao中使⽤⽅法如下:public User queryForObject(String sql, Map<String, Object> params) {return this.getNamedParameterJdbcTemplate().queryForObject(sql,params,new UserRowMapper());}在JUnit测试,代码如下:@Testpublic void getUser(){String sql = "select * from user where id = :id";Map<String,Object> map = new HashMap<>();map.put("id", 1);User user = dao.queryForObject(sql, map);System.out.println(user.getId());}输出结果为:1。
使用springjdbc遇到的一个性能问题
使⽤springjdbc遇到的⼀个性能问题使⽤JdbcTemplate的queryForList⽅法,返回特别慢,40多万结果集耗时超过6分钟。
双核CPU,占⽤率始终在50%,内存逐渐增长⾄2G左右。
进⾏debug跟进去看,看到jdbcTemplate调⽤jdbc返回ResultSet只⽤了30秒左右,之后就⼀直耗在extractData⽅法⾥。
该⽅法是⽤默认的RowMapper,先取得MetaData然后根据这个去⽣成Map。
对⽐⽅法:1. 使⽤纯jdbc对⽐,⼿⼯码代码,直接调⽤Map的put⽅法逐个⽣成Map并填充数据。
同样的sql,耗时40多秒,最后内存2G,其中根据ResultSet⽣成List<Map<String, Object>>的过程不超过10s。
2. 改⽤jdbcTemplate的public <T> List<T> query(String sql, RowMapper<T> rowMapper)⽅法,T填⼊Map<String, Object>,这样就跟queryForList⽅法返回值⼀样了,然后⾃⼰实现RowMapper,直接⽤Map的put⽅法填充数据。
实验结果跟直接⽤纯jdbc效率相同。
3. 使⽤纯jdbc,⾃⼰写⼀个实体类,把resultSet⾥的数据循环填⼊对象放到List⾥。
耗时40多秒,最后内存1.5G。
说明还是会省⼀点内存的。
但是性能提升有限。
结论:⽬前建议结果集较⼤时,最好使⽤public <T> List<T> query(String sql, RowMapper<T> rowMapper)⽅法替代qeuryForList⽅法,这样效率会有所提⾼。
未来估计jdbcTemplate的queryForList效率也会提升到相似⽔平。
Spring框架参考文档-5.0.0-中文完整版
Spring框架参考文档-5.0.0-中文完整版AuthorsRod Johnson , Juergen Hoeller , Keith Donald , Colin Sampaleanu , Rob Harrop , Thomas Risberg , Alef Arendsen , Darren Davison , Dmitriy Kopylenko , Mark Pollack , Thierry Templier , Erwin Vervaet , Portia Tung , Ben Hale , Adrian Colyer , John Lewis , Costin Leau , Mark Fisher , Sam Brannen , Ramnivas Laddad , Arjen Poutsma , Chris Beams , Tareq Abedrabbo , Andy Clement , Dave Syer , Oliver Gierke , Rossen Stoyanchev , Phillip Webb , Rob Winch , Brian Clozel , Stephane Nicoll , Sebastien Deleuze版本号:5.0.0.RELEASECopyright ? 2004-2016Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically.文档官网:https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/index.html现在官网的5.0.0已经在2017年9月28日出了release版,为此翻译了5.0.0版本(从4.3.10升级到此版本,如果还在使用4.3.10版本,请看本人的前一个版本),翻译前后历时15天,十多次的修改和校对。
Spring数据库连接池(JDBC)详解
Spring数据库连接池(JDBC)详解数据库连接池对⼀个简单的数据库应⽤,由于对数据库的访问不是很频繁,这时可以简单地在需要访问数据库时,就新创建⼀个连接,就完后就关闭它,这样做也不会带来什么性能上的开销。
但是对于⼀个复杂的数据库应⽤,情况就完全不同⽽,频繁的建⽴、关闭连接,会极⼤地减低系统的性能,因为对于连接的使⽤成了系统性能的瓶颈。
通过建⽴⼀个数据库连接池以及⼀套连接使⽤管理策略,可以达到连接复⽤的效果,使得⼀个数据库连接可以得到安全、⾼效的复⽤,避免了数据库连接频繁建⽴、关闭的开销。
数据库连接池的基本原理是在内部对象池中维护⼀定数量的数据库连接,并对外暴露数据库连接获取和返回⽅法。
如:外部使⽤者可通过getConnection⽅法获取连接,使⽤完毕后再通过releaseConnection⽅法将连接返回,注意此时连接并没有关闭,⽽是由连接池管理器回收,并为下⼀次使⽤做好准备。
数据库连接池技术带来的好处:1、资源重⽤由于数据库连接得到重⽤,避免了频繁创建、释放链接引起的⼤量性能开销。
在减少系统消耗的基础上,另⼀⽅⾯也增进了系统运⾏环境的平稳性(减少内存碎⽚以及数据库临时进⾏/线程数量)2、更快地系统响应速度数据库连接池在初始化过程中,往往已经创建了若⼲数据库连接池置于池中备⽤。
此时连接的初始化⼯作均已完成,对于业务请求处理⽽⾔,直接利⽤现有可⽤连接,避免了数据库连接初始化和释放过程的时间开销,从⽽缩减了系统整体响应时间3、统⼀的连接管理,避免数据库连接泄露在较为完备的数据库连接池实现中,可根据预先的连接占⽤超时设定,强制收回被占⽤连接,从⽽避免了常规数据库连接操作中可能出现的资源泄露。
⽬前数据库连接池产品是⾮常多的,主要有:1、dbcpdbcp,即DataBase Connection PoolApache出品,Spring开发组推荐使⽤的数据库连接池,开发较为活跃,是⼀个使⽤极为⼴泛的数据库连接池产品。
Spring和MyBatis的外文翻译
本科生毕业设计 (论文)外文翻译原文标题MVC Design Pattern for the multi frameworkdistributed applications using XML, spring and strutsframework译文标题使用XML,Spring和struts以MVC为设计模式的多分布式应用程序框架作者所在系别计算机与遥感信息技术学院作者所在班级B12511作者姓名王硕作者学号20124051117指导教师姓名耿炎指导教师职称院长完成时间2015 年1 月北华航天工业学院教务处制译文标题使用XML,Spring和struts以MVC为设计模式的多分布式应用程序框架原文标题MVC Design Pattern for the multi frameworkdistributed applications using XML, spring and struts framework作者Praveen Gupta 译名普利文·古塔国籍印度原文出处International Journal on Computer Science and Engineering 使用XML,Spring和struts以MVC为设计模式的多分布式应用程序框架摘要:模型-视图-控制器(MVC)是一个基本的设计模式,用来分离用户界面与业务的逻辑。
近些年来,应用程序的规模越来越大,而MVC设计模式可以弱耦合不同应用层的程序。
本文提出了一种基于J2EE平台上的网络,它扩展了MVC、XML 的应用程序框架,易于维护。
这是一个包括表示层、业务层、数据持久层和数据库层的多系统层,由于其代码的具有独立性,可维护性和可重用性大大提升。
在本文中,我们使用MVC实现spring和struts框架。
我们的研究显示,应用多个框架设计应用程序时,使用MVC概念能使应用程序转变为更容易、较单一的框架。
关键字:MVC,Spring,XML一介绍近些年来,web是非常复杂的问题。
Java编程语言外文翻译、英汉互译、中英对照
文档从互联网中收集,已重新修正排版,word格式支持编辑,如有帮助欢迎下载支持。
外文翻译原文及译文学院计算机学院专业计算机科学与技术班级学号姓名指导教师负责教师Java(programming language)Java is a general-purpose, concurrent, class-based, object-oriented computer program- -ming language that is specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere" (WORA), meaning that code that runs on one platform does not need to be recompiled to run on another. Java applications are typically compiled to byte code (class file) that can run on any Java virtual machine(JVM) regardless of computer architecture. Java is, as of 2012, one of the most popular programming languages in use, particularly for client-server web applications, with a reported 10 million users. Java was originally developed by James Gosling at Sun Microsystems (which has since merged into Oracle Corporation) and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++, but it has fewer low-level facilities than either of them.The original and reference implementation Java compilers, virtual machines, and class libraries were developed by Sun from 1991 and first released in 1995. As of May 2007, in compliance with the specifications of the Java Community Process, Sun relicensed most of its Java technologies under the GNU General Public License. Others have also developed alternative implementations of these Sun technologies, such as the GNU Compiler for Java and GNU Classpath.Java is a set of several computer software products and specifications from Sun Microsystems (which has since merged with Oracle Corporation), that together provide a system for developing application software and deploying it in across-platform computing environment. Java is used in a wide variety of computing platforms from embedded devices and mobile phones on the low end, to enterprise servers and supercomputers on the high end. While less common, Java appletsare sometimes used to provide improved and secure functions while browsing the World Wide Web on desktop computers.Writing in the Java programming language is the primary way to produce code that will be deployed as Java bytecode. There are, however, byte code compilers available forother languages such as Ada, JavaScript, Python, and Ruby. Several new languages have been designed to run natively on the Java Virtual Machine (JVM), such as Scala, Clojure and Groovy.Java syntax borrows heavily from C and C++, but object-oriented features are modeled after Smalltalk and Objective-C. Java eliminates certain low-level constructs such as pointers and has a very simple memory model where every object is allocated on the heap and all variables of object types are references. Memory management is handled through integrated automatic garbage collection performed by the JVM.An edition of the Java platform is the name for a bundle of related programs from Sun that allow for developing and running programs written in the Java programming language. The platform is not specific to any one processor or operating system, but rather an execution engine (called a virtual machine) and a compiler with a set of libraries that are implemented for various hardware and operating systems so that Java programs can run identically on all of them. The Java platform consists of several programs, each of which provides a portion of its overall capabilities. For example, the Java compiler, which converts Java source code into Java byte code (an intermediate language for the JVM), is provided as part of the Java Development Kit (JDK). The Java Runtime Environment(JRE), complementing the JVM with a just-in-time (JIT) compiler, converts intermediate byte code into native machine code on the fly. An extensive set of libraries are also part of the Java platform.The essential components in the platform are the Java language compiler, the libraries, and the runtime environment in which Java intermediate byte code "executes" according to the rules laid out in the virtual machine specification.In most modern operating systems (OSs), a large body of reusable code is provided to simplify the programmer's job. This code is typically provided as a set of dynamically loadable libraries that applications can call at runtime. Because the Java platform is not dependent on any specific operating system, applications cannot rely on any of the pre-existing OS libraries. Instead, the Java platform provides a comprehensive set of its own standard class libraries containing much of the same reusable functions commonly found in modern operating systems. Most of the system library is also written in Java. For instance, Swing library paints the user interface and handles the events itself, eliminatingmany subtle differences between how different platforms handle even similar components.The Java class libraries serve three purposes within the Java platform. First, like other standard code libraries, the Java libraries provide the programmer a well-known set of functions to perform common tasks, such as maintaining lists of items or performing complex string parsing. Second, the class libraries provide an abstract interface to tasks that would normally depend heavily on the hardware and operating system. Tasks such as network access and file access are often heavily intertwined with the distinctive implementations of each platform. The and java.io libraries implement an abstraction layer in native OS code, then provide a standard interface for the Java applications to perform those tasks. Finally, when some underlying platform does not support all of the features a Java application expects, the class libraries work to gracefully handle the absent components, either by emulation to provide a substitute, or at least by providing a consistent way to check for the presence of a specific feature.The success of Java and its write once, run anywhere concept has led to other similar efforts, notably the .NET Framework, appearing since 2002, which incorporates many of the successful aspects of Java. .NET in its complete form (Microsoft's implementation) is currently only fully available on Windows platforms, whereas Java is fully available on many platforms. .NET was built from the ground-up to support multiple programming languages, while the Java platform was initially built to support only the Java language, although many other languages have been made for JVM since..NET includes a Java-like language called Visual J# (formerly named J++) that is incompatible with the Java specification, and the associated class library mostly dates to the old JDK 1.1 version of the language. For these reasons, it is more a transitional language to switch from Java to the .NET platform, than a first class .NET language. Visual J# was discontinued with the release of Microsoft Visual Studio 2008. The existing version shipping with Visual Studio 2005will be supported until 2015 as per the product life-cycle strategy.In June and July 1994, after three days of brainstorming with John Gage, the Director of Science for Sun, Gosling, Joy, Naughton, Wayne Rosing, and Eric Schmidt, the team re-targeted the platform for the World Wide Web. They felt that with the advent of graphical web browsers like Mosaic, the Internet was on its way to evolving into the samehighly interactive medium that they had envisioned for cable TV. As a prototype, Naughton wrote a small browser, Web Runner (named after the movie Blade Runner), later renamed Hot Java.That year, the language was renamed Java after a trademark search revealed that Oak was used by Oak Technology. Although Java 1.0a was available for download in 1994, the first public release of Java was 1.0a2 with the Hot Java browser on May 23, 1995, announced by Gage at the Sun World conference. His announcement was accompanied by a surprise announcement by Marc Andreessen, Executive Vice President of Netscape Communications Corporation, that Netscape browsers would be including Java support. On January 9, 1996, the Java Soft group was formed by Sun Microsystems to develop the technology.Java编程语言Java是一种通用的,并发的,基于类的并且是面向对象的计算机编程语言,它是为实现尽可能地减少执行的依赖关系而特别设计的。
Spring源码—JDBC
Spring源码—JDBC前言内容主要参考自《Spring源码深度解析》一书,算是读书笔记或是原书的补充。
进入正文后可能会引来各种不适,毕竟阅读源码是件极其痛苦的事情。
本文主要涉及书中第八章的部分,依照书中内容以及个人理解对Spring源码进行了注释,详见Github仓库:https:///MrSorrow/spring-framework本章内容基于之前所说的Spring IOC 和 AOP功能,开始下一阶段有关应用方面的一些研究。
首先介绍Spring中关于JDBC给我们带来怎样的封装与支持。
I. JDBC连接MySQLJDBC连接数据库的流程1.在开发环境中加载指定数据库的驱动程序。
以数据库MySQL 为例,我们需要下载MySQL 支持JDBC 的驱动程序包(mysql-connector-java-xxx.jar);2.在 Java 代码中利用反射加载驱动程序,例如加载 MySQL 数据库驱动程序的代码为 Class.forName("com.mysql.jdbc.Driver");3.创建数据库连接对象。
通过 DriverManager 类来创建数据库连接对象 Connection 。
DriverManager 类作用于 Java 程序和 JDBC 驱动程序之间,用于检测所加载的驱动程序是否可以建立连接,然后通过 getConnection() 方法根据数据库的URL、用户名、密码创建一个JDBC Connection 对象,如:Connection connection = DriverManager.getConnecti on(“URL”, ”用户名”, ”密码”)。
其中,URL = 协议名 + IP地址(域名) + 端口 + 数据库名称;4.创建Statement 对象。
Statement 对象主要用于执行静态的SQL 语句并返回它所生成结果的对象。
通过数据库连接Connection 对象的createStatement() 可以创建一个Statement 对象。
spring的jdbc与传统的jdbc有什么区别,其核心类有那些-
spring的jdbc与传统的jdbc有什么区别,其核心类有那些?在J2EE的web应用里面配置spring非常简单,最简单的只需要把spring得ContextLoaderListener添加到你的web.xml文件里面就可以了,示例如下:org.springframework.web.context.ContextLoaderListener ContextLoaderListener是一个ServletContextListener, 它在你的web应用启动的时候初始化。
缺省情况下,它会在WEB-INF/applicationContext.xml文件找Spring的配置。
你可以通过定义一个元素名字为”contextConfigLocation”来改变Spring 配置文件的位置。
示例使用”org.springframework.jdbc.datasource.DriverManagerDataSou rce”数据源来配置数据库驱动。
示例如下:org.hsqldb.jdbcDriver jdbc:hsqldb:db/appfuse saspring提供了几个关于事务处理的类:TransactionDefinition //事务属性定义TranscationStatus //代表了当前的事务,可以提交,回滚。
PlatformTransactionManager这个是spring提供的用于管理事务的基础接口,其下有一个实现的抽象类AbstractPlatformTransac在context中定义DataSource,创建SessionFactoy,设置参数;DAO类继承HibernateDaoSupport,实现具体接口,从中获得HibernateTemplate进行具体操作。
在使用中如果遇到OpenSessionInView的问题,可以添加OpenSessionInViewFilter 或OpenSessionInViewIntercepto一个类需要用到某个接口的方法,我们需要将类A和接口B的实现关联起来,最简单的方法是类A中创建一个对于接口B的实现C 的实例,但这种方法显然两者的依赖(Dependency)太大了。
Spring的JdbcTemplate使用教程
Spring的JdbcTemplate使⽤教程Spring对数据库的操作在jdbc上⾯做了基本的封装,让开发者在操作数据库时只需关注SQL语句和查询结果处理器,即可完成功能(当然,只使⽤JdbcTemplate,还不能摆脱持久层实现类的编写)。
在配合spring的IoC功能,可以把DataSource注册到JdbcTemplate之中。
同时利⽤spring基于aop的事务即可完成简单的数据库CRUD操作。
JdbcTemplate的限定命名为org.springframework.jdbc.core.JdbcTemplate。
要使⽤JdbcTemlate需要导⼊spring-jdbc和spring-tx两个坐标。
⽅法说明:execute⽅法:可以⽤于执⾏任何SQL语句,⼀般⽤于执⾏DDL语句;update⽅法及batchUpdate⽅法:update⽅法⽤于执⾏新增、修改、删除等语句;batchUpdate⽅法⽤于执⾏批处理相关语句;query⽅法及queryForXXX⽅法:⽤于执⾏查询相关语句;call⽅法:⽤于执⾏存储过程、函数相关语句。
使⽤案例项⽬结构:项⽬代码POM.XML<dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.1.6.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.1.6.RELEASE</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.45</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.1.6.RELEASE</version></dependency></dependencies>实体类:public class Account implements Serializable {private Integer id;private String name;private Double money;//省略getter setter}public class Userinfo implements Serializable {private Integer id;private byte[] images; // 对应mysql数据库longBlob类型private String description; // 对应表的longText类型// 省略getter setter}相对应account表和userinfo表jdbc.propertiesjdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/spring_iocername=rootjdbc.password=adminjbbc配置类:public class JdbcConfig {@Value("${jdbc.driver}")private String driver;@Value("${jdbc.url}")private String url;@Value("${ername}")private String username;@Value("${jdbc.password}")private String password;/*** 创建数据源并存⼊Ioc容器* @return*/@Beanpublic DataSource createDataSource(){DriverManagerDataSource dataSource = new DriverManagerDataSource();dataSource.setDriverClassName(driver);dataSource.setUrl(url);dataSource.setUsername(username);dataSource.setPassword(password);return dataSource;}/*** 创建JdbcTemplate对象* @param dataSource* @return*/@Beanpublic JdbcTemplate createJdbcTemplate(DataSource dataSource){return new JdbcTemplate(dataSource);}// 操作clob和blob@Beanpublic LobHandler createLobHandler(){return new DefaultLobHandler();}}主配置类:@Configuration@Import(JdbcConfig.class)@PropertySource("classpath:jdbc.properties")public class SpringConfiguration {}测试类:/***注释部分为不同写法* 测试JdbcTemplate的使⽤*/@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = SpringConfiguration.class)public class SpringJdbcTemplateTest {@Autowiredprivate JdbcTemplate jdbcTemplate;@Testpublic void testSave(){jdbcTemplate.update("insert into account(money,name)values(?,?)",6789d,"userTest");}@Testpublic void testUpdate(){jdbcTemplate.update("update account set name=?,money=? where id=?","testZZZ",23456d,3);}@Testpublic void testDelete(){jdbcTemplate.update("delete from account where id = ? ",4);}@Testpublic void testFindOne(){// List<Account> accounts = jdbcTemplate.query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),1); // System.out.println(accounts.isEmpty()?"empty":accounts.get(0));// Account account = jdbcTemplate.queryForObject("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),1);// System.out.println(account);Account account = jdbcTemplate.query("select * from account where id = ?", new ResultSetExtractor<Account>() {@Overridepublic Account extractData(ResultSet rs) throws SQLException, DataAccessException {Account account1 = null;//1.判断结果集能往下⾛if(rs.next()){account1 = new Account();account1.setId(rs.getInt("id"));account1.setName(rs.getString("name"));account1.setMoney(rs.getDouble("money"));}return account1;}}, 1);System.out.println(account);}@Testpublic void testFindAll(){List<Account> accountList = jdbcTemplate.query("select * from account where money > ?",new BeanPropertyRowMapper<Account>(Account.class),999d); for(Account account : accountList){System.out.println(account);}}@Testpublic void testFindCount(){Integer count = jdbcTemplate.queryForObject("select count(*) from account where money > ?",Integer.class,999d);System.out.println(count);}@Testpublic void testQueryForList(){/*** 得到某个特定类型的集合。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
毕业设计(论文)外文文献翻译系别:XXXXXXXXXXXX专业:XXXXXXXXXXXX班级:XXXXXXXXXXXX学生姓名:XXX导师姓名:XXXX职称:XXXX起止时间:2009年3月2日至2009年6月12 日英文原文Spring contains a lot of functionality and features, which are well-organized in seven modules shown in the diagram below. This section discusses each the of modules in turn.The Core package is the most fundamental part of the framework and provides the Dependency Injection features allowing you to manage bean container functionality. The basic concept here is the BeanFactory, which provides a factory pattern removing the need for programmatic singletons and allowing you to decouple the configuration and specification of dependencies from your actual program logic.On top of the Core package sits the Context package, providing a way to access beans in a framework-style manner, somewhat resembling a JNDI-registry. The context package inherits its features from the beans package and adds support for text messaging using e.g. resource bundles, event-propagation, resource-loading and transparent creation of contexts by, for example, a servlet container.The DAO package provides a JDBC-abstraction layer that removes the need to do tedious JDBC coding and parsing of database-vendor specific error codes. Also, the JDBC package provides a way to do programmatic as well as declarative transaction management, not only for classes implementing special interfaces, but for all your POJOs (plain old java objects).The ORM package provides integration layers for popular object-relational mapping APIs, including JDO, Hibernate and iBatis. Using the ORM package you can use all those O/R-mappers in combination with all the other features Spring offers, like simple declarative transaction management mentioned before.Spring's AOP package provides an AOP Alliance compliant aspect-oriented programming implementation allowing you to define, for example, method-interceptors and pointcuts to cleanly decouple code implementing functionality that should logically speaking be separated. Using source-level metadata functionality you can incorporate all kinds of behavioral information into your code, a little like .NET attributes.Spring's Web package provides basic web-oriented integration features, such as multipart functionality, initialization of contexts using servlet listeners and a web-oriented application context. When using Spring together with WebWork or Struts, this is the package to integrate with.Spring's Web MVC package provides a Model-View-Controller implementation for web-applications. Spring's MVC implementation is not just any implementation, it provides a clean separation between domain model code and web forms and allows you to use all the other features of the Spring Framework like validation.Spring's web MVC framework is designed around a DispatcherServlet that dispatches requests to handlers, with configurable handler mappings, view resolution, locale and theme resolution as well as support for upload files. The default handler is a very simple Controller interface, just offering a ModelAndView handleRequest(request,response) method. This can already be used for application controllers, but you will prefer the included implementation hierarchy, consisting of, for example AbstractController, AbstractCommandController and SimpleFormController. Application controllers will typically be subclasses of those. Note that youcan choose an appropriate base class: If you don't have a form, you don't need a FormController. This is a major difference to Struts.You can use any object as a command or form object - there's no need to implement an interface or derive from a base class. Spring's data binding is highly flexible, for example, it treats type mismatches as validation errors that can be evaluated by the application, not as system errors. So you don't need to duplicate your business objects' properties as Strings in your form objects, just to be able to handle invalid submissions, or to convert the Strings properly. Instead, it is often preferable to bind directly to your business objects. This is another major difference to Struts which is built around required base classes like Action and ActionForm - for every type of action.Compared to WebWork, Spring has more differentiated object roles. It supports the notion of a Controller, an optional command or form object, and a model that gets passed to the view. The model will normally include the command or form object but also arbitrary reference data. Instead, a WebWork Action combines all those roles into one single object. WebWork does allow you to use existing business objects as part of your form, but only by making them bean properties of the respective Action class. Finally, the same Action instance that handles the request is used for evaluation and form population in the view. Thus, reference data needs to be modeled as bean properties of the Action too. These are arguably too many roles for one object.Spring's view resolution is extremely flexible. A Controller implementation can even write a view directly to the response, returning null as ModelAndView. In the normal case, a ModelAndView instance consists of a view name and a model Map, containing bean names and corresponding objects (like a command or form, containing reference data). View name resolution is highly configurable, either via bean names, via a properties file, or via your own ViewResolver implementation. The abstract model Map allows for complete abstraction of the view technology, without any hassle. Any renderer can be integrated directly, whether JSP, V elocity, or any other rendering technology. The model Map is simply transformed into an appropriate format, such as JSP request attributes or a Velocity template model..Pluggability of other MVC implementationsThere are several reasons why some projects will prefer to use other MVC implementations. Many teams expect to leverage their existing investment in skills and tools. In addition, there is a large body of knowledge and experience avalailable for the Struts framework. Thus, if you can live with Struts' architectural flaws, it can still be a viable choice for the web layer. The same applies to WebWork and other web MVC frameworks.If you don't want to use Spring's web MVC, but intend to leverage other solutions that Spring offers, you can integrate the web MVC framework of your choice with Spring easily. Simply start up a Spring root application context via its ContextLoaderListener, and access it via its ServletContext attribute (or Spring's respective helper method) from within a Struts or WebWork action. Note that there aren't any "plugins" involved, so no dedicated integration is necessary. From the web layer's point of view, you'll simply use Spring as a library, with the root application context instance as the entry point.All your registered beans and all of Spring's services can be at your fingertips even withoutSpring's web MVC. Spring doesn't compete with Struts or WebWork in this scenario, it just addresses the many areas that the pure web MVC frameworks don't, from bean configuration to data access and transaction handling. So you are able to enrich your application with a Spring middle tier and/or data access tier, even if you just want to use, for example, the transaction abstraction with JDBC or Hibernate.Features of Spring MVCSpring's web module provides a wealth of unique web support features, including:Clear separation of roles - controller, validator, command object, form object, model object, DispatcherServlet, handler mapping, view resolver, etc. Each role can be fulfilled by a specialized object.Powerful and straightforward configuration of both framework and application classes as JavaBeans, including easy referencing across contexts, such as from web controllers to business objects and validators.Adaptability, non-intrusiveness. Use whatever controller subclass you need (plain, command, form, wizard, multi-action, or a custom one) for a given scenario instead of deriving from a single controller for everything.Reusable business code - no need for duplication. You can use existing business objects as command or form objects instead of mirroring them in order to extend a particular framework base class.Customizable binding and validation - type mismatches as application-level validation errors that keep the offending value, localized date and number binding, etc instead of String-only form objects with manual parsing and conversion to business objects.Customizable handler mapping and view resolution - handler mapping and view resolution strategies range from simple URL-based configuration, to sophisticated, purpose-built resolution strategies. This is more flexible than some web MVC frameworks which mandate a particular technique.Flexible model transfer - model transfer via a name/value Map supports easy integration with any view technology.Customizable locale and theme resolution, support for JSPs with or without Spring tag library, support for JSTL, support for Velocity without the need for extra bridges, etc.A simple but powerful tag library that avoids HTML generation at any cost, allowing for maximum flexibility in terms of markup code.Data Access using O/R MappersSpring provides integration with Hibernate, JDO, Oracle TopLink, Apache OJB and iBATIS SQL Maps: in terms of resource management, DAO implementation support, and transaction strategies. For example for Hibernate, there is first-class support with lots of IoC convenience features, addressing many typical Hibernate integration issues. All of these support packages for O/R mappers comply with Spring's generic transaction and DAO exception hierarchies. There are usually two integration styles: either using Spring's DAO 'templates' or coding DAOs against plain Hibernate/JDO/TopLink/etc APIs. In both cases, DAOs can be configured through DependencyInjection and participate in Spring's resource and transaction management.Spring's adds significant support when using the O/R mapping layer of your choice to create data access applications. First of all, you should know that once you started using Spring's support for O/R mapping, you don't have to go all the way. No matter to what extent, you're invited to review and leverage the Spring approach, before deciding to take the effort and risk of building a similar infrastructure in-house. Much of the O/R mapping support, no matter what technology you're using may be used in a library style, as everything is designed as a set of reusable JavaBeans. Usage inside an ApplicationContext does provide additional benefits in terms of ease of configuration and deployment; as such, most examples in this section show configuration inside an ApplicationContext.Some of the the benefits of using Spring to create your O/R mapping DAOs include:Ease of testing. Spring's inversion of control approach makes it easy to swap the implementations and config locations of Hibernate SessionFactory instances, JDBC DataSources, transaction managers, and mapper object implementations (if needed). This makes it much easier to isolate and test each piece of persistence-related code in isolation.Common data access exceptions.Spring can wrap exceptions from you O/R mapping tool of choice, converting them from proprietary (potentially checked) exceptions to a common runtime DataAccessException hierarchy. This allows you to handle most persistence exceptions, which are non-recoverable, only in the appropriate layers, without annoying boilerplate catches/throws, and exception declarations. You can still trap and handle exceptions anywhere you need to. Remember that JDBC exceptions (including DB specific dialects) are also converted to the same hierarchy, meaning that you can perform some operations with JDBC within a consistent programming model.General resource management. Spring application contexts can handle the location and configuration of Hibernate SessionFactory instances, JDBC DataSources, iBATIS SQL Maps configuration objects, and other related resources. This makes these values easy to manage and change. Spring offers efficient, easy and safe handling of persistence resources. For example: Related code using Hibernate generally needs to use the same Hibernate Session for efficiency and proper transaction handling. Spring makes it easy to transparently create and bind a Session to the current thread, either by using an explicit 'template' wrapper class at the Java code level or by exposing a current Session through the Hibernate SessionFactory (for DAOs based on plain Hibernate3 API). Thus Spring solves many of the issues that repeatedly arise from typical Hibernate usage, for any transaction environment (local or JTA).Integrated transaction management. Spring allows you to wrap your O/R mapping code with either a declarative, AOP style method interceptor, or an explicit 'template' wrapper class at the Java code level. In either case, transaction semantics are handled for you, and proper transaction handling (rollback, etc) in case of exceptions is taken care of. As discussed below, you also get the benefit of being able to use and swap various transaction managers, without your Hibernate/JDO related code being affected: for example, between local transactions and JTA, with the same full services (such as declarative transactions) available in both scenarios. As an additional benefit,JDBC-related code can fully integrate transactionally with the code you use to do O/R mapping. This is useful for data access that's not suitable for O/R mapping, such as batch processing or streaming of BLOBs, which still needs to share common transactions with O/R mapping operations.To avoid vendor lock-in, and allow mix-and-match implementation strategies. While Hibernate is powerful, flexible, open source and free, it still uses a proprietary API. Furthermore one could argue that iBA TIS is a bit lightweight, although it's excellent for use in application that don't require complex O/R mapping strategies. Given the choice, it's usually desirable to implement major application functionality using standard or abstracted APIs, in case you need to switch to another implementation for reasons of functionality, performance, or any other concerns. For example, Spring's abstraction of Hibernate transactions and exceptions, along with its IoC approach which allows you to easily swap in mapper/DAO objects implementing data access functionality, makes it easy to isolate all Hibernate-specific code in one area of your application, without sacrificing any of the power of Hibernate. Higher level service code dealing with the DAOs has no need to know anything about their implementation. This approach has the additional benefit of making it easy to intentionally implement data access with a mix-and-match approach (i.e. some data access performed using Hibernate, and some using JDBC, others using iBATIS) in a non-intrusive fashion, potentially providing great benefits in terms of continuing to use legacy code or leveraging the strength of each technology.The Spring transaction abstractionSpring provides a consistent abstraction for transaction management. This abstraction is one of the most important of Spring's abstractions, and delivers the following benefits: Provides a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, iBA TIS Database Layer and JDO.Provides a simpler, easier to use, API for programmatic transaction management than most of these transaction APIsIntegrates with the Spring data access abstractionSupports Spring declarative transaction managementTraditionally, J2EE developers have had two choices for transaction management: to use global or local transactions. Global transactions are managed by the application server, using JTA. Local transactions are resource-specific: for example, a transaction associated with a JDBC connection. This choice had profound implications. Global transactions provide the ability to work with multiple transactional resources. (It's worth noting that most applications use a single transaction resource) With local transactions, the application server is not involved in transaction management, and cannot help ensure correctness across multiple resources.Global transactions have a significant downside. Code needs to use JTA: a cumbersome API to use (partly due to its exception model). Furthermore, a JTA UserTransaction normally needs to be obtained from JNDI: meaning that we need to use both JNDI and JTA to use JTA. Obviously all use of global transactions limits the reusability of application code, as JTA is normally only available in an application server environment.The preferred way to use global transactions was via EJB CMT (Container Managed Transaction): a form of declarative transaction management (as distinguished from programmatic transaction management). EJB CMT removes the need for transaction-related JNDI lookups--although of course the use of EJB itself necessitates the use of JNDI. It removes most--not all--need to write Java code to control transactions. The significant downside is that CMT is (obviously) tied to JTA and an application server environment; and that it's only available if we choose to implement business logic in EJBs, or at least behind a transactional EJB facade. The negatives around EJB in general are so great that this is not an attractive proposition, when there are alternatives for declarative transaction management.Local transactions may be easier to use, but also have significant disadvantages: They cannot work across multiple transactional resources, and tend to invade the programming model. For example, code that manages transactions using a JDBC connection cannot run within a global JTA transaction.Spring resolves these problems. It enables application developers to use a consistent programming model in any environment. You write your code once, and it can benefit from different transaction management strategies in different environments. Spring provides both declarative and programmatic transaction management. Declarative transaction management is preferred by most users, and recommended in most cases.With programmatic transaction management developers work with the Spring transaction abstraction, which can run over any underlying transaction infrastructure. With the preferred declarative model developers typically write little or no code related to transaction management, and hence don't depend on Spring's or any other transaction API.中文译文Core包是框架的最基础部分,并提供依赖注入(Dependency Injection)特性来使你可管理Bean容器功能。