(Reprinted little assembly) Spring Framework Introduction 2 - When Spring Hibernate event

http://www.ibm.com/developerworks/cn/java/wa-spring2/index.html

Naveen Balani continues his Spring series, introduced the Hibernate transaction with Spring aspect-oriented programming (AOP) integration of knowledge. The result is a persistence framework you can rely on.
In a period before this series, I introduced the Spring framework of seven modules, including the Spring AOP, and Inversion of Control (IOC) container. Then I use a simple example demonstrates the IOC mode (achieved by the Spring IOC container) the way how to integrate loosely coupled distributed systems.

Now, I start where my last end, with the last similar examples demonstrate Spring AOP and Spring Hibernate persistence support for declarative transactions, I first of these two technologies from the start of the study in depth.

Download the article source code. See Resources to visit the Spring framework and Apache Ant, run the sample application of this article need them.

Spring AOP

Software systems are usually multi-components, each component is responsible for a specific functional areas. However, these components often assume their responsibilities in addition to the core functionality. System services (such as logging, transaction management and security) often find themselves went to the other components of the field, the core functions of these components is something else. The result is the so-called "code entangled," or something more simple to say "mess." Aspect-oriented programming is an attempt to solve this problem programming it to enhance the focus of isolation as the core programming concepts.

When using the AOP is still defined in a local system of public functions, but you can define a statement of how and where to apply this function. If crosscutting concerns (such as logging and transaction management) and a modular, then do not modify each individual class, you can add new features to the code. Such modular aspect concerns known.

You know what?

May, at any Java ™ Enterprise Edition (J2EE) server functionality using the Spring framework. Moreover, you can adjust most of its features make it suitable for non-controlled environment. The central focus of Spring is not bound to support services in a particular J2EEE reusable business and data access objects. Across J2EE environments (Web or Enterprise JavaBean (EJB)), standalone applications, test environments and so on reuse of these objects, without any trouble.

An enterprise application as an example. Such applications often require similar security and transaction support services. Obviously, the support of these services can be written directly to the request for service among each class, but also hope to not have a lot of transactional context for the preparation of the same transaction code. If you use Spring AOP for transaction processing, you can arrange an appropriate statement of method calls, without having to individually arrange.

Spring AOP provides several ways, for JavaBean statement transaction. For example, TransactionProxyFactoryBean a convenient proxy class that can intercept method calls on the existing class, and the transaction context applied to the transaction bean. In the following example will see the practical application of this class.

Hibernate

Spring framework provides Hibernate, JDO, and iBATIS SQL Maps integration support. The support of the Hibernate Spring is the first level, the integration of many IOC convenience features, to solve many typical Hibernate integration issues. The support of the Hibernate framework consistent with Spring's generic transaction and data access objects (DAO) exception hierarchy.

Spring to use the selected OR mapping layer to create data access applications supported. Because all things are designed a set of reusable JavaBean, so no matter what technology choices, to the library format can access most of the OR mapping support for Spring. ApplicationContext or BeanFactory benefits within the OR mapping is to simplify the configuration and deployment.

Hibernate is the Java platform, a full-featured, open source OR mapping framework. Hibernate supports the development consistent with conventional ideas of persistent Java classes - including association, inheritance, polymorphism, complex and the Java collections framework. Hibernate query language (HQL) is designed as a micro-object-oriented SQL extension, which is the relationship between the object and the bridge between the world. Hibernate also supports the original SQL or Java-based standards and sample query expression query. Hibernate uses XML (*. hbm.xml) files to Java class mapped to the table, the JavaBean property is mapped to database tables.

Through JDBC technology to support all of the SQL database management system. Hibernate with all popular J2EE application servers and Web containers are well integrated.

Practical example

A bank application example allows you to see your work with Spring AOP and Hibernate how good. Bank account use case allows the user (Customer) in a transaction to open one or more bank accounts. Users can apply multiple bank accounts, you can choose a type of checking account or savings account type.

Application database (Cloudscape ™) to accommodate all customers and account information. In this example, assume that there is between the Customer and the Account Class 1: N association. In real life scenario, association may be required by the m: n model, to support the joint account.

Because users must be able to apply in a transaction more than one account, so first of all database interaction for the realization of a DOA model. And then to set the Spring AOP's TransactionProxyFactoryBean, and declare it to intercept method calls to the transaction context of application to the DOA.

Hibernate Practice

In the Spring Framework, JDBC DataSource or a Hibernate SessionFactory as such resources, in the application context can be achieved with the bean. Applications need to access resources only through the bean reference objects are good examples of such pre-defined reference can be (in this respect more in the next section). In Listing 1, you can see a sample banking application excerpt: XML defines the application context shows how to set up JDBC DataSource, and on top of a Hibernate SessionFactory.

Listing 1. JDBC DataSource and HibernateSessionFactory connection
<! - DataSource Property ->
<Bean
>
<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
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
>
<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 1 shows how the sample application database (a Cloudscape) configuration data source bean (exampleDataSource). exampleDatasource is connected to the Spring Hibernate's SessionFactory. Note that the *. hbm.xml specified sample application OR mapping files.

Data source and Session factory set up, the next step is to connect the DAO, the CustomerDAOImpl example, to use the SessionFactory. Next, insert the Spring of TransactionProxyFactoryBean, it will block the application of CustomerDAOImpl object method call, and a statement of affairs in the application on it.

In Listing 2 this example, CustomerDAOImpl class addCustomer is executed as part of the transaction, a transaction attribute PROPAGATION_REQUIRED. This property is equivalent to the EJB container TX_REQUIRED. If you want this method has been run in a transaction, you can use PROPAGATION_REQUIRED. If the transaction is already running, then the bean method will join the Service, or Spring's lightweight transaction manager starts a transaction. If you want to call the component services, always start a new transaction, you can use PROPAGATION_REQUIRES_NEW property.

Listing 2

<! - Pass the session factory to our CustomerDAO ->
<Bean
>
<property name="sessionFactory"> <ref local="exampleSessionFactory"/>
</ Property>
</ Bean>
<Bean
>
<property name="sessionFactory">
<ref bean="exampleSessionFactory"/>
</ Property>
</ Bean>
<Bean
>
<property name="transactionManager"> <ref local="transactionManager"/>
</ Property>
<property name="target"> <ref local="customerDAOTarget"/>
</ Property>
<property name="transactionAttributes">
<props>
<prop key="addCustomer"> PROPAGATION_REQUIRED </ prop>
</ Props>
</ Property>
</ Bean>

Application connection is complete, now to further view the source code.

Analysis of this!

If you've not done it yet, then please download the source code for this article. The release of the source zip file to your computer in any location, such as c: \. Will create a folder called SpringProjectPart2. src \ spring folder contains sample application of the Hibernate mapping files and Spring configuration files. src \ springexample \ hibernate file contains the application's source code.

Here will find two classes, namely, Customer and Account, with the Hibernate mapping files are mapped to two tables. Customer class on behalf of Customer Information, Account on behalf of the customer account information. As mentioned earlier, I take the two classes in accordance with the 1: N relationship modeling, that is, a Customer can have more than one Account. Listing 3 shows the Customer object Hibernate mapping file.

Listing 3. Customer object Hibernate mapping file
<? Xml version = "1.0"?>
<! DOCTYPE hibernate-mapping PUBLIC
"- / / Hibernate / Hibernate Mapping DTD 2.0 / / EN"
"Http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<Class
name = "springexample.hibernate.Customer"
table = "TBL_CUSTOMER"
dynamic-update = "false"
dynamic-insert = "false">
<Id
name = "id"
column = "CUSTOMER_ID"
type = "java.lang.Long"
unsaved-value = "-1"
>
<generator>
</ Generator>
</ Id>
<Set name = "accounts"
inverse = "true"
cascade = "all-delete-orphan">
<key column ="CUSTOMER_ID"/>
<one-to-many/>
</ Set>
<Property
name = "email"
type = "string"
update = "false"
insert = "true"
column = "CUSTOMER_EMAIL"
length = "82"
not-null = "true"
/>
<Property
name = "password"
type = "string"
update = "false"
insert = "true"
column = "CUSTOMER_PASSWORD"
length = "10"
not-null = "true"
/>
<Property
name = "userId"
type = "string"
update = "false"
insert = "true"
column = "CUSTOMER_USERID"
length = "12"
not-null = "true"
unique = "true"
/>
<Property
name = "firstName"
type = "string"
update = "false"
insert = "true"
column = "CUSTOMER_FIRSTNAME"
length = "25"
not-null = "true"
/>
<Property
name = "lastName"
type = "string"
update = "false"
insert = "true"
column = "CUSTOMER_LASTTNAME"
length = "25"
not-null = "true"

/>
</ Class>
</ Hibernate-mapping>

set name = "accounts" and to-many class tag specifies the relationship between Customer and Account. I'm still Account.hbm.xml file defines the mapping of Account objects.

CustomerDAOImpl.java on behalf of the application's DAO, its application into client and account database information. CustomerDAOImpl extends Spring's HibernateDaoSupport, it uses Spring HibernateTemplate simplifies session management. This can getHibernateTemplate () method to save or retrieve data. The following shows getCustomerAccountInfo () of the Customer to find, through getHibernateTemplate (). Find ways to use HQL get customer account information, 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 very easy to grasp. Now look at the practical application of the code!

Back to top

Run the application

To run the sample application, you must first download the Spring framework and all its dependent files. Then, the release of the framework to a particular location (eg c: \), this will create the folder C: \ spring-framework-1.2-rc2 (for the current release). Before proceeding must also download and released Apache Ant, and Cloudscape. Download Cloudscape after it released into the c: \, which will create the folder C: \ Cloudscape_10.0.

Next, release the source code to c: \, this will create SpringProject2 folder. Next, modify the build.xml file of the entry, with the location of Spring instead of the actual installation of C: \ spring-framework-1.2-rc2, with the location of the actual installation of Cloudscape instead of C: \ Program Files \ IBM \ Cloudscape_10.0.

Open a command prompt, enter SpringProject directory on the command line prompt, enter the following command: build.

This will build and run the CreateBankCustomerClient class, it creates the Customer class object, populate it with data, to create Account object, populate it and add it to the Customer object.

Then CreateBankCustomerClient calls CustomerDAOImpl.addCustomer class, add clients and account information. Once inserted to complete, CreateBankCustomerClient calls CustomerDAOImpl.getCustomerAccountInfo method, according to userid the clients and account information. If CreateBankCustomerClient successfully implemented, will see print in the console userid. Can also query the Cloudscape database search customer and account information.

Conclusion

Spring in the three-part series, Part 2, I introduced how to integrate Spring Hibernate and Spring AOP. The result is a robust persistence framework to support the statement of the realization of affairs.

The next article in this series and also the last article, I will introduce Spring's MVC module describes how to use it to simplify Web-based application creation.

分类:Java 时间:2010-06-01 人气:358
分享到:
blog comments powered by Disqus

相关文章

iOS 开发

Android 开发

Python 开发

JAVA 开发

开发语言

PHP 开发

Ruby 开发

搜索

前端开发

数据库

开发工具

开放平台

Javascript 开发

.NET 开发

云计算

服务器

Copyright (C) codeweblog.com, All Rights Reserved.

CodeWeblog.com 版权所有 黔ICP备15002463号-1

processed in 0.466 (s). 14 q(s)