11.1. Introduction Spring provides integration with Hibernate, JDO, and Ibatis SQL mappings in terms of resource management, DAO implementation support, and physical policies. For Hibernate, Spring uses many of the convenient features of IOC to provide first-class support to help you handle a lot of typical Hibernate integration. All of these are complied with Spring General transactions and DAO abnormal systems. When you choose to use the O / R mapping to create a data access application, the increase in Spring will provide you with important support. First of all, you should understand that once you use Spring's support for O / R mapping, you don't need to do everything yourself. We all recommend that you consider and use Spring solutions before deciding to consider and use Spring solutions before deciding to build a similar internal underlying structure. Regardless of the technique you use, most of the O / R mapping support can be used in library style, because all things are designed as a set of reusable JavaBeans. Using the ApplicationContext and BeanFactory is a simple benefit of configuring and deployment, so most examples of this chapter are configured in ApplicationContext. Benefits to build your ORM apps using Spring include: l Avoid binding special techniques, allowing Mix-And-Match implementation policies. Although Hibernate is very powerful, flexible, open source and free, but it still uses its own specific API. In addition, some people may argue: iBATIS is more light and useful in applications that do not require complex O / R mapping strategies. If you can choose, the standard or abstract API is used to implement the main application needs, usually better. In particular, when you may switch to another due to function, performance, or other aspects. For example, Spring is an IOC mechanism for Hibernate transactions and exceptions, and allows you to easily exchange the IOC mechanism for Mapper and DAO objects (implement data access). These two feature allow you to do not sacrifice Hibernate performance, Isolate the related code of Hibernate in your application. The high-level service code to handle DAO does not need to know the specific implementation of DAO. This method can easily use the MIX-And-Match scheme to achieve data access layers without interference (for example, in some places with hibernate, some places use iBATIs, other places, mix-and-match is conducive to handling left. Code and the strengths of various technologies (JDBC, Hibernate, Ibatis). l Test is simple. Spring's IOC makes it easy to replace different implementations, the location of the Hibernate SessionFacotory, DataSource, transaction management, and mapping objects. This is easily isolated from the various parts of the test persistent correlation code. l Ordinary resource management. Spring Application Context can handle sessionFactory, JDBC's DataSource, iBATIS's SQLMAPS configuration objects, such as Hibernate, and other relevant resources. This makes the values of these configurations easily managed and modified. Spring provides effective, simple and secure Hibernate session processing. Generally using Hibernate's code requires the same Hibernate session object to ensure effective and proper transaction. And Spring makes us easily created and bind a session to the current thread; you can use one of the following two ways: a declarative AOP method interceptor, or by using an external Template package class in Java code hierarchy achieve.
In this way, Spring solves the use of usage in many Hibernate forums. l Exception packaging. Spring can package Hibernate exceptions, turn them from proprietary, checked exception into a group of abstract runtime exception. This way you can only handle most of the unrecoverable exception in the appropriate layer, so that you avoid a lot of annoying catch / throw and abnormal statements. You can still capture and process anomalies where you need. Recalling that JDBC exceptions (including dialects related to DB) is converted to the same exception system, which means you can process JDBC operations in a consistent programming model. l Integrated transaction management. Spring allows you to package your ORM code, intercept the declaration, or use the external Template packaging class in the code level. Regardless of which, transaction-related semantics will be handled for you, in case an abnormality will help you do your proper transaction (such as rollback). Just like we have to discuss below, you can use and replace a variety of Transaction Managers, but will not affect your Hibernate-related code. BEST, JDBC-related code can be completely and hibernate code Integrate Transactionaly. This is very useful for dealing with features that do not have Hibernate or iBATIIS. 11.2. Hibernate11.2.1. The typical application of resource management is often repeated resource management code. Many projects try to create their own solutions to solve this problem, sometimes, sometimes sacrificing appropriate fault processing for programming. For proper resource processing Spring advocates a remarkable solution: using Templating IoC, such as the foundation class, and callback interface, or provides an AOP interceptor. The basic class is responsible for fixed resource processing, and converting specific exceptions into unchecked exception systems. Spring introduces a DAO abnormality system that can be applied to any data access policy. For situations directly using JDBC, the JDBCTemplate class mentioned in the previous section is responsible for handling Connection, correcting SQLEXEption into a DataAccessException system (including the SQL error code associated with the database into meaningful exceptions). It also supports JTA and JDBC transactions through their respective Spring Transaction Managers. Spring also provides support for Hibernate and JDO: a HibernateTemplate / JDTEMPlate is similar to JDBCTemplate, HibernateInterceptor / JDointerceptor, and a Hibernate / JDO Transaction Manager. The main purpose is to clearly divide the application level regardless of the data access and transaction technology; the coupling between the application object is loose. Business objects (bo) no longer rely on data access and transaction policies; no longer have hard-coded resources lookup; no longer replace Singletons; no longer customized service registration. A simple and robust solution is connected to the application, and allows them to reuse the container as much as possible. Although all data access technologies can be used independently, it is better to combine Spring Application Context, which provides XML-based configuration and normal JavaBean instances that are unrelated to Spring.
In a typical Spring app, many important objects are javabeans: Data Access Template, Data Access Objects (Use Template), Transaction Managers, Business Objects (Using Data Access Objects and Transaction Managers), Web View Resolvers, Web Controller Business objects, etc. 11.2.2. Defining Resources in Application Context To avoid smoothing application objects, Spring allows you to define resources such as JDBC DataSource, Hibernate SessionFactory as defined in the Application Context. Applications that need to access these resources require only references to these predefined instances. The following code demonstrates how to create a JDBC DataSource and Hibernate SessionFactory:
For external objects, there is no requirement for specific interfaces, it only needs to provide a Hibernate's sessionFacotry. It can be obtained from anywhere, and the relatively suitable method is the bean references obtained from Spring's Application Context: BEAN attribute setter by simple setsessionFactory. The following code shows a definition of a DAO in Application Context, which references the sessionFactory, which is defined above, and shows the specific implementation of a DAO method.
public class ProductDaoImpl implements productDao {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 product.category =?", category, Hibernate.STRING); // results List Do some processing returnrate;}});}} A Callback implementation can be used in any Hibernate data access. HibernateTemplate will ensure that sessions are properly turned on and off and will automatically participate in transactions. The Template instance is a thread secure, reusable, thus being held as an instance variable of an external class. For simple steps, such as simple Find, Load, SaveorUpdate, or Delete calls, HibernateTemplate provides an optional simple way to replace this line of Callback implementation. In addition, Spring provides a simple HibernatedAosupport base class, which provides a setSessionFactory () method to accept a sessionFactory, getSessionFactory () and gethibernateTemplate () method is used. This can have 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);.}} 11.2.4. Applying the AOP Interceptor (Interceptor) instead of Templatespring's AOP HibernateInterceptor is a replacement as HibernateTemplate, which writes Hibernate code directly in a delegated TRY / CATCH block, and an interceptor definition in Application Context, replacing the Callback implementation. The following demonstrates the DAO in the application context, Interceptor and definitions proxy, as well as to achieve a particular DAO method:
public class ProductDaoImpl extends HibernateDaoSupport implements ProdctDao {public List loadProdctsByCategory (final String category) throws MyException {Session session = SessionFactoryUtils.getSession (getSessionFactory (), false); try {List result = session.find ( "from test.Product product where product ? .category = ", category, Hibernate.STRING); if (result == null) {throw new MyException (" invalid search result ");} return result;} catch (HibernateException ex) {throw SessionFactoryUtils.convertHibernateAccessException (ex) This method must have a HibernateInterceptor to work. The "false" flag in the GetSession method is to ensure that sessionFactoryUTils creates a new one. If there is already a sessionHolder in the thread, such as a HibernateTransactionManager transaction, the sessionFactoryUtils will definitely participate. HibernateTemplate uses sessionFactoryUtils internally, they are the same underlying structure. The most important advantage of HibernateInterceptor is that it is allowed to throw Checked applications in the data access code, and HibernateTemplate is strictly restricted in the callback. It is worth noting that we can postpone all kinds of Check and throw an abnormality to the callback. The main disadvantage of Interceptor is that it needs special assembly in Context. HibernateTemplate's easy way is simpler in many scenes. 11.2.5. Programmed transactions are divided on these low-level data access services, which can be divided on the high level of the application, allowing transactions across multiple operations. Here is the same as the associated business object (BO), which only requires a Spring PlatformTransactionManager. Like SessionFactory, this Manager can come from anywhere, but it is best to be a bean references set by the SetTransactionManager method. The following demonstrates the definition of a Transaction Manager and a business object in the Srping Application Context, and how the specific business method is implemented:
public class ProductServiceImpl implements ProductService {private ProductDao productDao; public void setProductDao (ProductDao productDao) {this.productDao = productDao;} public void increasePriceOfAllProductsInCategory (final String category) {List productsToChange = this.productDAO.loadProductsByCategory (category); ...} ...} Like HibernateInterceptor, TransactionInterceptor allows any Checked application exception to thrown in the Callback code, while TransactionTemplate strictly requires unchecked exception in Callback. TransactionTemplate will trigger a Rollback when you spur, or when the transaction is marked by TransactionsTatus as Rollback-Only. TransactionInterceptor performs the same operation by default, but it allows the ROLLBACK policy to each method. A simple and optional way to create a declarative transaction is: TransactionProxyFactoryBean, especially without other AOP Interceptors involved. For a specific target bean, TransactionProxyFactory uses transaction to configure yourself in combination with Proxy. This reduces the configuration to configure a target bean and a definition of an Proxy BEAN (less interceptor definition). In addition, you don't need to specify which interface or class defined in the transaction method.
For distributed transactions across multiple Hibernate sessionFacotry, just simply define the JTATRRAASACTIONMANAGER as a transaction policy as a transaction policy. Every DAO is a respective sessionFactory reference through the bean property. If all the underlying JDBC DataSource is a container that supports transaction, as long as a business object uses the JTATRRANSACTIONMANAGER policy, it can divide the transaction across multiple DAOs and multiple session factories without special treatments:
This allows the mixed Hibernate / JDBC data access to be transaction-divided on high levels without JTA, as long as they use the same database. 11.2.8. Applying Spring Management Application Bean A Spring Application Context can be read by many different contexts, such as FileSystemXmlapplicationContext and ClassPathXMLApplicationContext, and XMLWebApplicationContext. By default, a web application gets root context from "Web-INF / ApplicationContext.xml". In all Spring applications, the Application Context defined in the XML file connects all relevant Application Beans, including Hibernate Session Factory, and data access and business objects (just like the beans defined above). Most of them will not be aware of being managed by the Spring container, even when they cooperate with other beans, because they only follow JavaBeans's specifications. A bean property and can represent value parameters, or other cooperation beans. The following bean definition can be used as part of the Spring Web MVC Context, and accessing Business Beans in root application context. All data traffic or
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"); 11.2.9. Container Resources VS Local Resource Spring Resource Management Taking the simple switch between JNDI sessionFactory and Local's sessionFactory, this is the case for JNDI DataSource, and do not need to modify a line of code. Place the resource definition in the container or placed in the application locally. It is mainly determined by the transaction policy used. Compared with Spring defined local sessionFactory, a manually registered JNDI SessionFactory does not provide any extra benefits. If you register with Hibernate's JCA connector, there is a significant benefit to participate in the JTA transaction, especially in EJB. An important benefit of Spring transaction support is not dependent on any container. Using non-JTA policy configurations, the program will work properly in an independent or test environment. Especially in a typical single database transaction, this will be a lightweight and powerful replacement of JTA. When using a local EJB SLSB to drive the transaction, although you may only access a database and use SLSBS's declarative transactions with SLSBS, you still have to rely on EJB containers and JTA. Programming uses JTA's alternatives still requires a J2EE environment. JTA introduces container dependence not only in this regard and in JNDI DataSource. For non-Spring, JTA-driven Hibernate transactions, in order to make Caching in the appropriate JVM level, you must use the Hibernate JCA connector or additional Hibernate transaction code and configured JTA transactions. Spring driver can use the local defined Hibernate SessionFacotry to work, just like working with local JDBC DataSource (of course, access must be a separate database). So you only need to return to Spring's JTA transaction strategy when facing distributed transaction needs. It is important to note that a JCA connector requires a deployment step of a specific container, and first supports JCA. This is more troublesome than deploying a simple web application than using local resource definitions and Spring driver transactions. And you usually require an enterprise version of the container, such as WebLogic's Express version does not provide JCA. A Spring app that only uses local resources and transactions only across a database (not required JTA, JCA or EJB) in any J2EE Web container, such as Tomcat, Resin, and even ordinary Jetty. More, this intermediate layer can be simply reused in desktop applications or test cases.
In summary: If you don't use EJB, stick to the creation of local sessionFactory and Spring HibernateTransactionManager or JTATRRANSACTIONMANAGER. You can get all the benefits of Caching and distributed transactions, including any container deployment, including the appropriate JVM level. The JNDISSIONFACTORY JNDI registration is only beneficial in EJB through the JCA connector. 11.2.10. Example The PETClinic in the Spring Issue provides an optional DAO implementation and an Application Context profile (for HibernaT, JDBC, and Apache OJB). Therefore, PETClinic can be used as a workable example application to clarify how to use Hibernate in the Spring Web application. It also uses declarative transactions under different transaction strategies. 11.3. JDOTODO11.4. iBATISSpring supports IBATIS SQLMAPS 1.3.x and 2.0 through org.springframework.orm.ibatis. IBATIS support is very similar to Hibernate support, which supports the same Template style programming, and like Hibernate, iBatis support is also working with Spring's exception system, he will let you like Spring all IOC features. 11.4.1.1.3.x and 2.0 Overview and distinguish Spring provides support for IBATIS SQLMAPS1.3 and 2.0. Let us first take a look at the difference between two. 11.4.2. Creating SQLMAP Use IBATIS SQLMAPS to create a configuration file that creates the relevant relationship between statements and results. Spring will be responsible for using SQLMAPFactoryBean or SQLMAPClientFactoryBean to read these profiles, where the latter class is used in combination with SQLMAPS2.0. public class Account {private String name; private String email; public String getName () {return this.name;} public void setName (String name) {this.name = name;} public String getEmail () {return this.email; } Public void setemail (string email) {this.email = email;}} To map this class, we must create the following SQLMAP. By using the query, we can use Email Addersses later to get Users. Account.xml:
public class SqlMapAccountDao extends SqlMapDaoSupport implements AccountDao {public Account getAccount (String email) throws DataAccessException {Account acc = new Account (); acc.setEmail (); return (Account) getSqlMapTemplate () executeQueryForObject ( "getAccountByEmail", email);.} Public void INSERTACCOUNT (Account Account) Throws DataAccessException ("InsertAccount", Account);}} As you can see, we use SQLMapTemplate to perform queries. Spring will use SQLMapFactoryBean to initialize SQLMAP when you create SQLMapAccountDao as shown below. Everything is ready: