In this seriesPrevious PeriodI introduced seven modules of the Spring framework, including Spring AOP and IOC containers. Then I used a simple example to demonstrate how the IOC mode (implemented by the Spring IoC container) integrates distributed systems in a loosely coupled manner.
Now, from where I ended last time, I used a similar example to demonstrate declarative transaction processing supported by Spring AOP and spring hibernate, so I started with an in-depth study of these two technologies.
Download the source code of this Article. SeeReferencesAccess the Spring framework and Apache ant and run the sample applications in this article.
Spring AOP
A software system usually consists of multiple components, each of which is responsible for a specific functional area. However, these components often take extra responsibilities beyond their core functions. System services (such as logs, transaction management, and security) often find themselves in the field of other components, and the core responsibilities of these components are other things. The result is the so-called "code tangle", or simply "a mess ". Aspect-oriented programming is a programming technique that attempts to solve this problem. It promotes the isolation of concerns to the core programming concept.
When using AOP, the public functions of the system are still defined in one place, but can be declared.HowAndWhereApply this function. If you modularize the cross-cutting concerns (such as log and transaction management), you can add new features to the code without modifying each individual class. This modular focus is calledAspect.
|
Do you know? You can use the Spring framework functions on any Java Enterprise Edition (J2EE) server. In addition, you can adjust most of its functions to adapt to uncontrolled environments. The central focus of spring is to support reusable businesses and data access objects that are not bound to a specific j2eee service. This type of object can be reused across J2EE environments (web or Enterprise JavaBean (EJB), independent applications, and test environments without any trouble. |
|
Take an enterprise application as an example. Such applications generally require services similar to security and transaction support. Obviously, the support of these services can be directly written into every class of the required service, but it is also expected that the same transaction processing code is not required for a large number of transactional contexts. If Spring AOP is used for transaction processing, you can schedule appropriate method calls in a declarative manner without having to schedule them one by one.
Spring AOP provides several aspects to declare transactions for JavaBean. For example,TransactionProxyFactoryBean
It is a convenient proxy class that can intercept method calls to existing classes and apply the transaction context to the transaction bean. The following example shows the actual application of this class.
Hibernate
The Spring framework provides integration support for hibernate, JDO, and ibatis SQL maps. Spring supports hibernate at the first level. It integrates many convenient features of IOC and solves many typical hibernate integration problems. The Framework's support for hibernate conforms to spring's general transaction and Data Access Object (DAO) exception hierarchies.
Spring provides support for using the selected or ing layer to create data access applications. Because everything is designed as a set of reusable JavaBean, No matter what technology you choose, you can access the or ing support of most spring in the library format.ApplicationContext
OrBeanFactory
The internal or ing feature simplifies configuration and deployment.
Hibernate is a fully functional, open-source or ing framework on the Java platform. Hibernate supports developing persistent classes that conform to the conventional Java philosophy-including Association, inheritance, polymorphism, composition, and Java Collection frameworks. The Hibernate query language (hql) is designed as a micro-object-oriented extension of SQL, which serves as a bridge between objects and the relational world. Hibernate also supports expressing queries using raw SQL or Java-based standard and sample queries. Hibernate uses XML (*. HBM. xml) File maps the Java class to the table and an attribute to the database table.
Supports all SQL database management systems through JDBC technology. Hibernate is well integrated with all popular J2EE application servers and web containers.
Actual Example
A bank application example allows you to see how well Spring AOP and hibernate work together. Bank account use cases allow users (Customer
) Opens one or more bank accounts in a transaction. You can apply for multiple bank accounts. You can select a check account or a savings account.
The application database (cloudscape) contains all customer and account information. In this example, assume thatCustomer
AndAccount
Between classes1: N. In actual scenariosM: NModeling to support joint accounts.
Because you must be able to apply for multiple accounts in a transaction, you must first implement a DOA mode for database interaction. Then set the Spring AOPTransactionProxyFactoryBean
To intercept method calls and apply the transaction context to the DOA declarative.
Hibernate practices
In the Spring frameworkDataSource
Or hibernateSessionFactory
Such resources can be implemented using bean in the application context. The application objects that need to access resources only need to get the reference of such pre-defined instances through bean reference (in this regardNext section). In listing 1, you can see an excerpt from the sample banking application: the XML application context definition shows how to set JDBCDataSource
And put a hibernateSessionFactory
.
Listing 1. JDBC datasource and hibernatesessionfactory connection
<!-- DataSource Property --><bean id="exampleDataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName"> <value>org.apache.derby.jdbc.EmbeddedDriver</value> </property> <property name="url"> <value>jdbc:derby:springexample;create=true</value> </property></bean> <!-- Database Property --><bean id="exampleHibernateProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="properties"> <props> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.dialect">net.sf.hibernate.dialect.DerbyDialect</prop> <prop key="hibernate.query.substitutions">true 'T', false 'F'</prop> <prop key="hibernate.show_sql">false</prop> <prop key="hibernate.c3p0.minPoolSize">5</prop> <prop key="hibernate.c3p0.maxPoolSize">20</prop> <prop key="hibernate.c3p0.timeout">600</prop> <prop key="hibernate.c3p0.max_statement">50</prop> <prop key="hibernate.c3p0.testConnectionOnCheckout">false</prop> </props> </property></bean><!-- Hibernate SessionFactory --><bean id="exampleSessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean"> <property name="dataSource"> <ref local="exampleDataSource"/> </property> <property name="hibernateProperties"> <ref bean="exampleHibernateProperties" /> </property> <!-- OR mapping files. --> <property name="mappingResources"> <list> <value>Customer.hbm.xml</value> <value>Account.hbm.xml</value> </list> </property></bean>
|
Listing 1Shows how to configure the data source Bean (exampleDataSource
).exampleDatasource
Connected to spring hibernateSessionFactory
. Note:*. HBM. xmlSpecifies the or ing file of the sample application.
After the data source and session factory are set, the next step is to connect in Dao.CustomerDAOImpl
In the exampleSessionFactory
. Next, insertTransactionProxyFactoryBean
It interceptsCustomerDAOImpl
The method of the object to be called, and the application of the transaction on it is declarative.
InListing 2In this example,CustomerDAOImpl
ClassaddCustomer
The method is executed as part of the transaction and has a transaction attribute.PROPAGATION_REQUIRED
. This attribute is equivalent toTX_REQUIRED
. If you want to keep this method running in a transaction, you can usePROPAGATION_REQUIRED
. If the transaction is already running, the bean method is added to the transaction. Otherwise, the lightweight Transaction Manager of spring starts a transaction. You can usePROPAGATION_REQUIRES_NEW
Attribute.
After the application connection is complete, you can view the source code further.
Analyze this!
If you haven't done this before, pleaseDownload the source code of this Article. Release the source ZIP file to any location on the computer, suchC :/. CreatesSpringprojectpart2.Src/springThe folder contains the hibernate ing file and spring configuration file of the sample application.Src/springexample/hibernateThe file contains the source code of the application.
Here we will find two classes:Customer
AndAccount
, Which are mapped to two tables using the hibernate ing file.Customer
Class represents customer information,Account
Account information that represents the customer. As mentioned above1: NLink modeling, that is,Customer
You can have multipleAccount
. Listing 3 showsCustomer
Object hibernate ing file.
Listing 3. hibernate ing file of the customer object
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 2.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
|
set name="accounts"
And a pair of multi-class labels specifiedCustomer
AndAccount
. I am stillAccount. HBM. xmlThe file definesAccount
Object ing.
CustomerDAOImpl.java
The Dao representing the application, which inserts the customer and account information in the application database.CustomerDAOImpl
Extends spring'sHibernateDaoSupport
It uses spring hibernatetemplate to simplify session management. In this way, you can usegetHibernateTemplate()
Method to save or retrieve data. ThegetCustomerAccountInfo()
PairCustomer
ProceedSearch, ThroughgetHibernateTemplate().find
Use hql to obtain the customer's account information, as shown in Listing 4.
Listing 4. DAO implementation
public class CustomerDAOImpl extends HibernateDaoSupport implements CustomerDAO{ public void addCustomer(Customer customer) { getHibernateTemplate().save(customer); // TODO Auto-generated method stub } public Customer getCustomerAccountInfo(Customer customer) { Customer cust = null; List list = getHibernateTemplate().find("from Customer customer " + "where customer.userId = ?" , customer.getUserId(),Hibernate.STRING); if(list.size() > 0){ cust = (Customer) list.get(0); } return cust; }
|
All of these should be easy to grasp. Now let's look at the actual application of the code!
Run the application
To run the sample application, you must firstDownload Spring frameworkAnd all its dependent files. Next, release the framework to a certain position (for exampleC :/). This creates a folder.C:/spring-framework-1.2-rc2(For the current release ). You must download and release it before continuing.Apache antAndCloudscape. After downloading cloudscape, release itC :/This will create foldersC:/cloudscape_10.0.
Next, release the source codeC :/This createsSpringproject2Folder. Next, modifyBuild. xmlFile portal, which is replaced by the actual installation location of springC:/spring-framework-1.2-rc2In place of the actual cloudscape installation location.C:/program files/IBM/cloudscape_10.0.
Open the command line prompt and enterSpringprojectDirectory, enter the following command at the command line prompt:build
.
This will build and runCreateBankCustomerClient
Class, it will createCustomer
Class Object, fill it with data, createAccount
Object, fill it in, and add itCustomer
Object.
ThenCreateBankCustomerClient
YesCustomerDAOImpl.addCustomer
Class to add customer and account information. Once the insertion is complete,CreateBankCustomerClient
YesCustomerDAOImpl.getCustomerAccountInfo
Method, accordinguserid
Obtain the customer and account information. IfCreateBankCustomerClient
The execution is successful and the output is displayed on the console.userid
. You can also query the cloudscape database to retrieve the customer and account information.
Conclusion
InSpring SeriesIn section 2nd, I introduced how to integrate Spring Hibernate and Spring AOP. The result is a strong persistence framework that supports declarative transactions.