Spring's lightweight Bean container provides IOC type assembly capabilities for business objects, DAO objects, and resources (such as JDBC Data Sources, or Hibernate SessionFactorie et al.). Spring uses an XML format application profile to manually manually manage the selectivity of single instance objects or factory objects by parsing custom property files. Since Spring makes non-intrusionability as an important goal, it is possible to complete the configuration of Spring's own interfaces and classes can be done by Spring configuration management. This concept can be applied to any environment, no matter what you develop is a J2EE web application or a desktop app is even just an applet.
In applications using Hibernate, Spring's usual transaction management should especially pay attention to DAO objects. Its purpose is to isolate data access and transaction, so that the transactional business object is not tied with any special data access or transaction policy, which does not affect the reuse of the business object. This division can be implemented either transactionTemplate as a programming manner, or can be implemented in a manner as a "TOP) transactional interceptor. Whether it is a local Hibernate / JDBC transaction, or the JTA transaction supports a transactional strategy outside the object, which is a very useful selection for local stateless sessions Beans.
The Spring HibernateTemplate class provides a simple way to implement Hibernate-based Dao objects without having to care about how to get Hibernate's session instance, and do not have to care for multi-participation transactions. There is no need to use TRY-CATCH blocks, there is no need for transaction checks. A simple Hibernate access method completely solves some troubles! Whether in the case of multiple DAO interfaces or in multi-party transactions, Spring makes multiple DAO objects seamlessly work together. For example: Some DAO objects may be based on the implementation of Plain JDBC, more suitable for manual abnormal processing via Spring's JDBCTemplate.
You can use many Spring features separately because all objects of Spring are a collection of JavaBean objects designed to be multiplexed. Don't be discouraged because Spring can provide a complete framework! When using other Spring features, the application configuration concept is an additional feature and is not a must-have feature. Anyway, when you want to build an inherent infrastructure like Spring, there is no limit on the way of using Spring.
1. Introduction: Resource Management
Typical business applications often cause confusion due to duplicate resource management code. Many projects tried to solve this problem with their own methods. Sometimes Spring advocates a simple way for appropriate resource management: that is, inverted control, invection of control, For example: the basic class uses a callback interface, or applies an AOP interceptor. Its basic core is appropriate resource handling and converts special APIs to the base exception of unchecked.
Spring introduces a DAO exception layer for any data access policy. For direct JDBCs, JDBCTemplate classes focus on connection processing and focus on SQLException to proper DataAccessException, including converting special database SQL errors to meaningful exceptions. Spring supports JTA and JDBC transactions via different transaction management objects. Spring also provides support for Hibernate and JDO, which supports HibernateTemplate classes and JDEMPLATE classes similar to the JDBCTemplate class, and HibernateInterceptor classes, JDointerceptor classes, and Hibernate, JDO transaction management classes. The most important purpose is to distinguish the level of the application, and deliver data access and transaction processing with application objects. All business objects no longer rely on data access or transaction policies. No more hard-coded resource lookup code, no longer have a single case object, no longer need a custom service registration.
All individual data access features do not require Spring, which can be used separately without letting Spring know, and can also be assembled through Spring application configuration (providing an XML-based configuration and cross-references to ordinary JavaBean instances). In a typical Spring application, most important objects are ordinary JavaBean: Data Access Templates, Data Access Objects (Objects to Template Objects with Data), Transaction Management Objects and Business Objects (Use Data Access Objects and Transaction Objects), the web represents an exploded object, the web control object (objects of the business object), and more.
2. The resource definition in the application configuration
To avoid application objects hard code, Spring allows a bean to be defined as a bean as JDBC DataSource or Hibernate SessionFactory in the application configuration. Applications If you need access to resources, you only need to receive a reference to the previously defined instance by a bean reference (DAO definition in the next section). The following content references from an application configuration definition, showing how to create a JDBC Datasource and a Hibernate's sessionFactory:
You can also use a JNDI to find sessionFactory, but it is usually not required for applications other than EJB environments (refer to the discussion of the "Container Resources VS Local Resources).
3. Inversion Control: Template and Pickup
The basic programming mode of the template is like you will see below, as for the method, just like any custom data access object or the object of the service. In addition to providing it to provide a Hibernate's sessionFactory, there is no limit to the trust of the object around the object. Although it is best to use a bean reference from a Spring application configuration to obtain it, but then you can get it from anywhere. Subsequent reference fragments include a configuration in the Spring application configuration to the DAO definition, which references examples in which the SESSIONFACTORY, and a DAO method are implemented.
Property>
bean>
...
beans>
Public Class ProductDaoImpl Implements Productda {
Private sessionFactory sessionFactory;
Public void setsessionFactory (sessionFactory sessionFactory) {
THIS.SESSIONFACTORY = sessionFactory;
}
Public List loadProductSBycategory (FINAL STRING CATEGORY) {
HibernateTemplate HibernateTemplate =
New HibernateTemplate (this.SessionFactory);
Return (List) HibernateTemplate.execute (
New hibernateCallback () {
Public Object Doinhibernate (session session) throws hibernateException {
List result = session.find (
"From test.product product where produter =?",
Category, Hibernate.String;
// do some further stuff with the result list
Return Result;
}
}
);
}
}
A callback implementation can be effectively used in any Hibernate data access. In any case, it is managed by HibernateTemplate to manage the session and automatic multi-party transactions. Template instances are thread security and reusable, so they can do variables for other classes.
For simple single steps, like Find, Load, SaveorUpdate, or delete, HibernateTemplate provides a more convenient choice to replace the callback of a row. In addition, Spring provides a convenient basic class, which is the HibernatedAosupport class that provides a SetSessionFactory method to accept a sessionFactory while providing the GetSessionFactory and gethibernateTemplate methods for its inheritance class. Combine these, allowing a very simple DAO implementation for typical needs:
Public Class ProductDaoImpl Extends Hibernatedaosupport IMPLEments Productdao {Public List LoadProductSbycategory (String Category) {
Return gethibernateTemplate (). Find
"from test.product product where product.category =?", category,
Hibernate.string;
}
}
4. Apply an AOP interceptor instead of a template
Another option other than HibernateTemplate is use Spring's AOP HibernateInterceptor. Use the Hibernate code directly in a delegated TRY / CATCH block, and cooperate with the corresponding interceptor configuration in the application configuration instead of the callback. The following segment shows the respective definitions of DAO, Interceptor, and Proxy in a Spring application configuration, and give an example of a DAO method implementation:
...
Class = "org.springframework.orm.hibernate.hibernateInterceptor"> Property> bean> Property> bean> Property> list> Property> bean> ... beans> Public Class ProductDaoImpl Extends Hibernatedaosupport IMPLEments Productda { Public List LoadProductSbycategory (FINAL STRING CATEGORY) THROWS MyException { Session session = sessionFactoryUtils.getations (GetSessionFactory (), False; Try { List result = session.find ( "From test.product product where produter =?", Category, Hibernate.String; IF (result == null) { Throw New MyException ("Invalid Search Result"); } Return Result; } Catch (HibernateException EX) { Throw sessionFactoryUtils.ConvertHibernateAccessException (ex); } } } This method will only work normally when there is a HibernateInterceptor that it works, and HibernateInterceptor is the turn off after the opening and method call of the SESSION in the process before the method calls. The "false" flag in the GetSession method is to confirm that the session must already exist. If no one session is found, SessionFactoryUtils will create one for it. If there is already a session handle binding on this thread, such as binding by a HibernateTransactionManager transaction, in any case, SessionFactoryUTils will automatically access this session. HibernateTemplate also uses SessionFactoryUtils on the ground, which is basically the same as the above way. The main benefit of HibernateInterceptor is that it allows the Checked Application Exception in the data access code, and HibernateTemplate can only throw unchecked Exceptions due to the restricted callback. Note that this we can postpone their own inspections while throwing the application exception after the callback. The main disadvantage of intercepting methods is that it needs special configurations in the configuration. HibernateTemplate is a simple and easy way in most cases. 5. Program transaction division Above this underlying data access service, transaction processing can be divided on a higher application layer to form some operations. There is no restriction in addition to a Spring's PlatformTransactionManager object, there is no restrictions. Similarly, you can get them anywhere, but it is more suitable via the setTransactionManage method via the stepTransactionManage method, like ProductDao to get the same via a setProductDao method. The following reference fragment shows the definition of transaction management objects and business objects in a Spring application configuration, and also provides an example of a business method implementation: ... Class = "org.springframework.orm.hibernate.hibernateTransactionManager"> Property> bean> Property> bean> beans> Public Class ProductServiceImpl Implements PRODSERVICE { Private PlatformTransactionManager TransactionManager; Private productdao productda; Public void setTransactionManager (PlatformTransactionManager TransactionManager) { THIS.TRANSACTIONMANAGER = TransactionManager; } Public void setProductdao (ProductDao Productdao) { THIS.PRODUCTDAO = PRODUCTDAO; } Public Void IncreasePRiceOfallProductSIncategory (FINAL STRING CATEGORY) { TransactionTemplate TransactionTemplate = New TransactionTemplate (this.TransactionManager); TransactionTemplate.SetPropagationBehavior (TransactionsDefinition.propagation_required); TransactionTemplate.execute ( New TransactionCallbackwithOutResult () { Public void dointransactionwithoutResult (TransactionsTatus Status) { List productstochange = productdao.loadproductsbycategory (category); ... } } ); } } 6. Declarative transaction division We can also choose AOP TransactionInterceptor using Spring to replace transaction division code by defining interceptor configurations in application configuration. This allows us to keep business objects independently of repeated transaction classification code in each business object. In addition, changes in transaction behavior and isolation hierarchy can be changed through a profile without affecting the implementation of business objects. ... Class = "org.springframework.orm.hibernate.hibernateTransactionManager"> Property> bean> Class = "Org.springframework.transaction.interceptor.transactionintercePtor"> Property> Product.ProductService.Increaseprice * = PropAgation_required Product.ProductService.SOMEOTHERBUSINESSMETHOD = Propagation_Mandatory value> Property> bean> Property> bean> Property> list> Property> bean> beans> Public Class ProductServiceImpl Implements PRODSERVICE { Private productdao productda; Public void setProductdao (ProductDao Productdao) { THIS.PRODUCTDAO = PRODUCTDAO; } Public Void IncreasePRiceOfallProductSIncategory (FINAL STRING CATEGORY) { List productStochange = this.productdao.loadProductSbycategory (category); ... } } As with HibernateInterceptor the same, TransactionInterceptor allows any checked application exception thrown from the callback code, while TransactionTemplate subject to restrictions in its internal callback throw unchecked exceptions, in the event of a situation when the unchecked application exception of, TransactionTemplate will lead to a rollback or the transaction Marked by the application (through the transaction status) as a rollback. TransactionInterceptor is also the same behavior by default, but allowing rollback policies to each method. A convenient way to establish a declarative transaction is to use TransactionProxyFactoryBean, especially if there is no other AOP interceptor, TransactionProxyFactoryBean will jointly define the transaction configured for the agent's own and a special target bean. This will reduce the configuration of a proxy bean corresponding to a target bean. In addition, you don't have to specify which interface or which class must define a transaction method. ... Class = "org.springframework.orm.hibernate.hibernateTransactionManager"> Property> bean> Property> bean> Class = "org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> Property> Property> prOPS> Property> bean> beans> 7. Transaction management strategy For Hibernate applications, whether or TransactionTemplate TransactionInterceptor are commissioned to verify the actual transaction PlatformTransactionManager instance, it may be a HibernateTransactionManager (of a single Hibernate SessionFactory using a ThreadLocal Session) or may be a JtaTransactionManager (agent container JTA subsystem). Even you can use a custom PlatformTransactionManager implementation. If you choose to transfer transaction management from a local Hibernate transaction to be managed by JTA, for example, when your application is deployed, it is just a matter of changing the configuration. Just simply change Hibernate's transaction management to JTA transaction implementation. All transactional division and data access can continue to work without any changes, because they are all ordinary transaction management APIs. For distributed transactions spanning multiple Hibernate's Session Factories, just United JTATRRRANSACTIONMANAGERs are just as transaction policies as a transaction policy. Every DAO will get a special sessionFactory reference through their respective bean properties. If all this is in the following JDBC data source is a transactional container, a business object can divide a transaction across a lot of Dao and a lot of Session Factories without having to do special processing, is the same for using JTATRRRRRANSACTIONMANAGER as a transaction strategy. Property> bean> Property> bean> Class = "org.springframework.orm.hibernate.localsessionFactoryBean"> list> Property> prOPs> Property> Property> bean> Class = "org.springframework.orm.hibernate.localsessionFactoryBean"> list> Property> prOPS> Property> Property> bean> Class = "org.springframework.transaction.jta.jtatransactionmanager" /> Property> bean> Property> bean> Property> Property> bean> Class = "org.springframework.transaction.interceptor.TransactionProxyFactoryBean> Property> Property> prOPS> Property> bean> beans> Whether HibernateTransactionManager or JTATRRRANSACTIONMANAGER allows appropriate cache processing for Hibernate in JVM hierarchy - no container - provide special transaction lookups or JCA connectors (not using EJB initiating transactions). In addition, HibernateTransactionManager outputs a JDBC connection for usual JDBC access code. This allows the transaction partitioning at a high level to mix Hibernate and JDBC without JTA, as long as it is just accessing a database! 8. BEAN using Spring Management Application A Spring application configuration definition can be loaded by multiple configurations, from FileSystemXmlapplicationContext and ClassPathXMLApplicationContext to XMLWebApplicationContext. This allows you to re-use Spring management data access and business objects in a variety of environments. By default, a web app will have its own definition root configuration in "Web-INF / ApplicationContext.xml". In any Spring application, an application configuration defines all related beans for applications in an XML format to assemble, from Hibernate's session factory to custom data access and business objects (like all Beans above Like that). Most of them don't need a Spring container to know them, even if they work together with other beans, because they are just a collaboration between JavaBean. The following bean definition may be part of a Spring Web's MVC configuration to access the configuration of the business object. Property> bean> Spring's Web Controller is referenced to all services and data access objects they need via a bean, so they do not need to make any manual bean lookups in the application configuration. But when using Spring Manage Beans is used for Struts or in an EJB implementation, or when an applet is used to manually find a bean. Therefore, Spring's beans can be used anywhere. Perhaps just need to be a reference to an application configuration, or create it from a servlet configuration property of a web container, or from a file or class path resource. ApplicationContext context = WebApplicationContextUtils.GetWebApplicationContext (servletContext); ProductService ProductService = (ProductService) Context.getBean ("MyProductService"); ApplicationContext context = New filesystemxmlapplicationContext ("c: /mycontext.xml); ProductService ProductService = (ProductService) Context.getBean ("MyProductService"); ApplicationContext context = New classpathxmlapplicationContext ("MyContext.xml"); ProductService ProductService = (ProductService) Context.getBean ("MyProductService"); 9. Container resource VS local resources Spring resource management allows you to choose between JNDI SessionFactory and a local sessionFactory, which is also allowed to make a selection between a JNDI DataSource with local DataSource without changing the application's code. Saving resource definitions in the container is still preserved locally, mainly a transaction policy. Compare a local sessionFactory with a Spring and a manually registered JNDI SessionFactory without any benefits. If you register through the JCA connector through Hibernate, there will be a significant benefit to join the JTA transaction, especially for EJB. The advantage of an important Spring transaction is that it is not bound to any container. Definitions include a policy, which can work independently or working in a test environment. Especially for a typical database transaction, this is a very lightweight and powerful choice for JTA. When using local EJB SLSB transactions, you will rely on EJB containers and JTA- even if you just access a database, even if you just use SLSBs to declare transactions via CMT. Choosing a JTA programming also requires a J2EE environment. JTA is not just including container dependence on JTA itself and JNDI data sources. For Hibernate transactions that do not use Spring, you must use the HibernateJCA connector or transaction code to write Hibernate in the appropriate JVM buffer layer to configure JTA transaction. In the case of only one database, Spring-driven transactions can cooperate with a local defined Hibernate, just as in combination with a local JDBC data source. Therefore, when faced with distributed transaction needs, you only need to convert JTA transaction policies to Spring. It is important to note that a JCA connector requires a special container deployment step, and it is clear that JCA is first supported. This is more controversial than deploying a simple web application than using local resource definitions and Spring driver transactions. And you often need the company's version of the container support, and JCA is not available like WebLogic Express. A Spring app that uses local resources and transactions with a database can be worked in any J2EE's Web container, and the web container does not have to support JTA, JCA, and EJBs, such as: Tomcat, Resin, and even smallest Jetty. In addition, such an intermediate layer can be easily applied to the desktop application or in the test kit. All considered things include: If you don't use EJB, insist on using the local sessionFactory, use SpringHibernateTransactionManager or JTATRRANSACTIONMANAGER, you will get all the benefits of cache and distribution of JVM layers appropriately, without causing any arguments for container deployment . The JNDI registration of the sessionFactory of a Hibernate via the JCA connector is just a significant value in the case of using EJB. 10. Skeletons and examples Configuring a J2EE for a J2EE using Spring and Hibernate is best to look at "Typical web application" Skeletons in Spring Framework, which gives a variety of data sources suitable for JDBC and Hibernate applications. And the configuration of the transaction management, take a closer look at the configuration of the transaction interceptor, and it also shows you how to configure the AOP interceptor. In the 1.0 M2 version of Spring, the example PETClinic provides the selection of DAO implementations and application configurations for JDBC and Hibernate. PetClinic can be used as a workable simple application to use Hibernate in a Spring Web application, and also include business division based on different transaction policies. Links Spring Framework Website Spring Framework Documentation